2012-10-05 63 views
0

我想添加一个NSString到一个NSMutableArray(它将只保存NSStrings)。我没有收到任何错误,但是当我查询数组的count时,它返回零,表示它没有添加该值。这里是我的代码(其获得一些XML,这绝对是100%的工作是):NSString不会将自己添加到NSMutableArray

// get an array of genres for this game 
NSArray *genreList = [self getAllItems:@"//genre" fileName:[NSURL URLWithString:queryURL]]; 
int numberOfGenres = [genreList count]; 
NSLog(@"This game has %u genres", numberOfGenres); 

这NSLog的正确报告,在XML结果条目的数量,通常是1-5之间。

// put the genre names from that array into the current game's object 
if (numberOfGenres > 0) { 
    for (int i = 0; i < numberOfGenres; i++) { 
     NSString *currentGenreName = [NSString stringWithString:[[genreList objectAtIndex:i] objectForKey:@"name"]]; 
     [currentGame.gameGenres addObject: currentGenreName]; 
     NSLog(@"I added a genre to %@, called %@.", currentGame.gameName, currentGenreName); 
    } 
} 

此NSLog还可以正确报告游戏的标题以及XML树中的标题。

// save current game to game list 
NSLog(@"I'm about to save %@ to the array, with its %u genres", currentGame.gameName, [currentGame.gameGenres count]); 
[_listOfGamesReturnedFromSearch addObject:currentGame]; 

这最后的NSLog总是报告流派的数量为零。如果我稍后查询_listOfGamesReturnedFromSearch数组,它将保存其他属性(名称),但流派计数为零 - 由于某种原因它不保存它们。

任何想法?

+0

你在哪里声明并初始化你的数组? – DrummerB

+0

@DrummerB显然没有。 – 2012-10-05 13:29:29

+0

从我完成obj-c开始已经有一段时间了,但是您确定currentGame.gameGenres未设置为零吗? –

回答

2

这是不分配和初始化数组的一个典型症状 - 因此它保持为nil并且一直忽略所有发送的消息。 Alloc-init它,它会工作。

+0

我已经完成了对象本身的alloc init,我是否还需要初始化它的所有属性?如果是这样,我应该在对象类的init方法中这样做吗? – Luke

+0

是的,你需要分配/初始化你的属性,通常你在init方法中这样做。 – DrummerB

+1

@lukech如果你alloc-init一个对象,所有的实例变量将被初始化为零...现在阅读Objective-C运行时参考。 – 2012-10-05 13:32:25