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 i from 1 to 18, and I would like to add an object to an NSMutableArray in this loop. Right now I have:
chapterList = [[NSMutableArra开发者_如何学JAVAy 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,
chapterList = [[NSMutableArray alloc] initWithCapacity:18];
for (int i = 1; i<19; i++)
{
[chapterList addObject:[NSString stringWithFormat:@"Chapter %d",i]];
}
good luck
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.
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.
精彩评论