3

I am very new to Objective-C with Cocoa, and I need help.

I have a for statement in which I loop i from 1 to 18, and I would like to add an object to an NSMutableArray in this loop. Right now I have:

chapterList = [[NSMutableArray alloc] initWithCapacity:18];
for (int i = 1; i<19; i++)
{
    [chapterList addObject:@"Chapter"+ i];
}

I would like it to add the objects, chapter 1, chapter 2, chapter 3... , chapter 18. I have no idea how to do this, or even if it is possible. Is there a better way? Please Help

Thanks in advance,

1
  • You mean you want strings that say Chapter 1, Chapter 2 etc.? Commented Mar 21, 2011 at 4:21

3 Answers 3

3
chapterList = [[NSMutableArray alloc] initWithCapacity:18];
for (int i = 1; i<19; i++)
{
    [chapterList addObject:[NSString stringWithFormat:@"Chapter %d",i]];
}

good luck

Sign up to request clarification or add additional context in comments.

Comments

2

Try:

[chapterList addObject:[NSString stringWithFormat:@"Chapter %d", i]];

In Objective-C/Cocoa you can't append to a string using the + operator. You either have to use things like stringWithFormat: to build the complete string that you want, or things like stringByAppendingString: to append data to an existing string. The NSString reference might be a useful place to start.

Comments

1

If you're wanting strings that merely say Chapter 1, Chapter 2, you can just do this:

chapterList = [[NSMutableArray alloc] initWithCapacity:18];
for (int i = 1; i<19; i++) {
    [chapterList addObject:[NSString stringWithFormat:@"Chapter %d",i]];
}

And don't forget to release the array when you're done, as you're calling alloc on it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.