Adding object to NSMutableArray works just for the first time

时间:2022-09-25 18:48:14

In my app I have a method that, when I press a button, adds a string to a NSMutableArray which is the model for a UITableView.

在我的应用程序中,我有一个方法,当我按下按钮时,将一个字符串添加到NSMutableArray,这是UITableView的模型。

 - (void)addPressed:(id)sender
{
    NSString *string = @"aString";
    [self.array addObject:string];
    NSLog(@"Array count: %d",[self.array count]);
    [self.tableView reloadData];
}

Problem is that the adding works the first time only if I press twice the button connected to this action I get this output:

问题是只有当我按两次连接到此操作的按钮时,添加才会第一次运行我得到此输出:

2012-09-16 21:33:08.766 iUni[3066:c07] Array count: 1 //Which is fine since it worked
2012-09-16 21:33:08.952 iUni[3066:c07] Array count: 1 //Now count should be 2!!

Anyone has a guess on why is this happening?

任何人都猜测为什么会这样?

I added the @property, synthesized it and lazy instatiated it this way:

我添加了@property,合成它并以这种方式懒惰instatiated:

- (NSMutableArray *)array
{
    if (!_array) {
        NSMutableArray *array = [NSMutableArray array];
        _array = array;
    }
    return _array;
}

1 个解决方案

#1


3  

Your array is being created as an unowned (autoreleased, actually) object, which means that it is destroyed shortly after each time your accessor is called. It is then recreated the next time you access it, which gives you a new, empty array.

您的数组被创建为无主(自动释放,实际上)对象,这意味着每次调用访问器后它都会被销毁。然后在下次访问它时重新创建它,这会为您提供一个新的空数组。

You need to create an owned version of the array to store into your instance variable:

您需要创建要存储到实例变量中的数组的自有版本:

if (!_array) {
    _array = [[NSMutableArray alloc] init];
    // Note no need to create a temp variable.
}
return _array;

You could also turn on ARC, which would have taken care of this for you and is a good idea anyways.

您也可以启用ARC,它可以为您处理这个问题,无论如何都是个好主意。

#1


3  

Your array is being created as an unowned (autoreleased, actually) object, which means that it is destroyed shortly after each time your accessor is called. It is then recreated the next time you access it, which gives you a new, empty array.

您的数组被创建为无主(自动释放,实际上)对象,这意味着每次调用访问器后它都会被销毁。然后在下次访问它时重新创建它,这会为您提供一个新的空数组。

You need to create an owned version of the array to store into your instance variable:

您需要创建要存储到实例变量中的数组的自有版本:

if (!_array) {
    _array = [[NSMutableArray alloc] init];
    // Note no need to create a temp variable.
}
return _array;

You could also turn on ARC, which would have taken care of this for you and is a good idea anyways.

您也可以启用ARC,它可以为您处理这个问题,无论如何都是个好主意。