简体   繁体   中英

Adding object to NSMutableArray works just for the first time

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.

 - (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:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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