简体   繁体   English

将自定义对象添加到可变数组时出现问题

[英]Problem adding custom objects to Mutable Array

quick question regarding Array's in xcode. 关于数组在xcode的快速问题。 I have ht efollowing code, which is supposed to go through an array of strings which it has got through php and JSON, and trun these strings into a custom object with the strings as the ivars for the object then add that object to a new array: 我有以下代码,应该通过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]);
}

The code does return the correct values using NSLog(@"%@", article.description); 该代码确实使用NSLog(@"%@", article.description);返回正确的值NSLog(@"%@", article.description); but not the correct length for the new array and it only adds one value to the array which is the string for article.description which makes no sense to me. 但不是新数组的正确长度,它只会向数组中添加一个值,这是article.description的字符串,这对我来说毫无意义。 The list array contains 2 elements each of which are arrays in themselves containing the strings. 列表数组包含2个元素,每个元素本身就是包含字符串的数组。

You're recreating the articleArray in every loop. 您将在每个循环中重新创建articleArray。 Declarate it outside, and it will work: 在外部声明它,它将起作用:

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]);
}

You also may want to use the nicer for(NSArray *listElement in list) syntax instead. 您可能还想使用更好的for(NSArray * listlist in list)语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM