将自定义对象添加到Mutable Array时出现问题

时间:2010-11-16 12:06:22

标签: iphone xcode nsmutablearray

关于xcode中的数组的快速问题。我有以下代码,它应该通过php和JSON获得的字符串数组,并将这些字符串转换为自定义对象,字符串作为对象的ivars然后将该对象添加到新数组:

for (int i = 0; i<[list count]; i++) {
        Article *article = [[Article alloc] init]; //creates custom object
        article.uid = [[list objectAtIndex:i] objectAtIndex:0];
        article.title = [[list objectAtIndex:i] objectAtIndex:1]; //adds string as ivars
        article.description = [[list objectAtIndex:i] objectAtIndex:2];
        articleArray = [[NSMutableArray alloc] init]; //inits the new array
        [articleArray addObject:article]; //should add the object but seems to fail
        [article release]; //releases the object
        NSLog(@"%@", article.description);
    }
    NSLog(@"%d", [articleArray count]);
    NSLog([articleArray description]);
}

代码确实使用NSLog(@"%@", article.description);返回正确的值但不是新数组的正确长度,它只向数组添加一个值,这是article.description的字符串,这对我没有意义。 list数组包含2个元素,每个元素都是包含字符串的数组。

1 个答案:

答案 0 :(得分:6)

你在每个循环中重新创建articleArray。在外面声明它,它将起作用:

NSMutableArray *articleArray = [[NSMutableArray alloc] init]; //inits the new array
for (int i = 0; i<[list count]; i++) {
        Article *article = [[Article alloc] init]; //creates custom object
        article.uid = [[list objectAtIndex:i] objectAtIndex:0];
        article.title = [[list objectAtIndex:i] objectAtIndex:1]; //adds string as ivars
        article.description = [[list objectAtIndex:i] objectAtIndex:2];
        [articleArray addObject:article]; //should add the object but seems to fail
        [article release]; //releases the object
        NSLog(@"%@", article.description);
    }
    NSLog(@"%d", [articleArray count]);
    NSLog([articleArray description]);
}

您也可能希望使用更好的(NSArray * listElement in list)语法。