Adding a string followed by an int to an array

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

I have a for statement in which I loop from 1 to 18, and I would like to add an object to 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 for him to add 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,

+3
source share
3 answers

Try:

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

Objective-C/Cocoa , +. , stringWithFormat:, , , , stringByAppendingString:, . NSString .

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

+3

If you need a line that simply say Chapter 1, Chapter 2you can simply 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 free the array when you're done, when you call allocon it.

+1
source

All Articles