2011-03-21 81 views
3

我对Cocoa Objective-C非常陌生,我需要帮助。向数组中添加一个字符串后跟一个int

我有一个for循环我从1到18的语句,我想在这个循环中添加一个对象到NSMutableArray。现在,我有:

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

我想它添加的对象,第一章,第二章,第三章...,第18章。我不知道如何做到这一点,或者即使是可能。有没有更好的办法?请帮助提前

感谢,

+0

你的意思是你想要说'第一章',第二章等的字符串? – 2011-03-21 04:21:03

回答

2

尝试:

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

在Objective-C /可可使用+运营商不能追加到一个字符串。您必须使用像stringWithFormat:这样的东西来构建所需的完整字符串,或者使用像stringByAppendingString:这样的东西来将数据追加到现有字符串。 NSString reference可能是一个有用的开始。

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

好运

1

如果你想串,仅仅说Chapter 1Chapter 2,你可以这样做:

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

而且不要忘记释放数组当你做,因为你打电话alloc就可以了。

相关问题