为什么我的对象没有添加到数组中?

时间:2011-05-15 06:59:56

标签: iphone objective-c ios nsmutablearray

我无法将对象添加到简单的NSMutableArray中。我旁边有一个Objective-c参考,并让它适用于简单的字符串。但我需要添加实际对象。请告诉我这里我做错了什么。

代码:

TBXMLElement *hubImage = [TBXML childElementNamed:@"image" parentElement:[TBXML childElementNamed:@"images" parentElement:pieceXML]];
if(hubImage) {
    do {
        HubPieceImage *tmpImage = [[HubPieceImage alloc] initWithXML:hubImage];
        [self.images addObject: tmpImage];
        HubPieceImage *tmpImage2 = [self.images lastObject];
        NSLog(@"image  : %@",  tmpImage.asset_url);
        NSLog(@"image 2: %@",  tmpImage2.asset_url);
    } while ((hubImage = hubImage->nextSibling));
}
NSLog(@"count  : %i", [self.images count]);

在循环浏览两个对象时,在日志中返回此内容:

image  : http://farm6.static.flickr.com/5215/5533190578_4v629a79e5.jpg
image 2: (null)
image  : http://farm3.static.flickr.com/2774/5416668522_fdcr19aed3.jpg
image 2: (null)
count  : 0

实际上阵列似乎根本没有填满(考虑数:0)

感谢您的帮助

3 个答案:

答案 0 :(得分:2)

只是为了好玩,试试这个:

    HubPieceImage *tmpImage = [[HubPieceImage alloc] initWithXML:hubImage];
    NSAssert(self.images, @"Whoops! self.images is NULL");
    [self.images addObject: tmpImage];

可能是你的问题!也就是说,self.images可能是零。

答案 1 :(得分:0)

我发现了问题!
我没有像这样初始化数组:

self.images = [[NSMutableArray alloc] init];

答案 2 :(得分:0)

images = [[NSMutableArray alloc] initWithCapacity:10];

请确保在

之前调用了alloc和init