在for循环的每次迭代后,NSMutableArray都会被释放?

时间:2012-05-02 07:22:24

标签: objective-c arrays memory-management nsmutablearray

我有一个对象数组,我想根据对象的某个值(即self.example.value)进行排序。我创建了多个可变数组:

NSMutableArray *array1, *array2, *array3 = [[NSMutableArray alloc] initWithObjects: nil];

然后使用for循环遍历原始数组。如果对象匹配条件(self.example.value == someValue)。我将对象添加到上面创建的一个新数组中。但是,当我稍后开始使用数组时,我注意到它们是空的。使用调试器我注意到以下内容:

for (customClass *object in arrayOfObject){ //starting here the debugger has NONE of the arrays created above

    if (object.value == someValue){//after performing this line, the debugger shows array1 in memory BUT nothing in it EVEN if the 'if' statement isn't TRUE.
        [array1 addobject:object]; 
    } else if (object.value == someOtherValue){//after performing this line, the debugger shows array2 in memory BUT nothing in it EVEN if the 'if' statement isn't TRUE. 
        [array2 addobject:object]; 
    } //and so forth

基本上,for循环的每次迭代都会清除上面创建的数组。随着代码的进展,无论'if'语句是否为TRUE,都会分配数组,但不会填充数组。我在这里缺少什么?

1 个答案:

答案 0 :(得分:5)

你只是为array3分配一个数组,所以其他两个要么是垃圾,要么是nil,这取决于你在这里处理的变量类型。我想你想要:

NSMutableArray *array1 = [[NSMutableArray alloc] init];
NSMutableArray *array2 = [[NSMutableArray alloc] init];
NSMutableArray *array3 = [[NSMutableArray alloc] init];