2011-03-21 98 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就可以了。

相關問題