简体   繁体   中英

Setting pointers to nil, objective-c

I'm a bit confused about pointer memory being new to programming. So I add a UIBarButtonItem based on when a UITabBarController is selected like so:

NSMutableArray *barItems = [[self.MainToolbar items] mutableCopy];
    if (_sortButton == nil) {
        _sortButton = [[UIBarButtonItem alloc] initWithTitle:@"Sort" style:UIBarButtonItemStyleBordered target:self action:@selector(sortButtonPressed:)];
        [barItems insertObject:_sortButton atIndex:0];
        [self.MainToolbar setItems:barItems];
        [_sortButton release];
    }

I tried removing the UIBarButton by checking if _sortButton is nil like this:

    if (_sortButton != nil) {
        // self.SortButton = nil;  // I NEEDED THIS
        NSMutableArray *barItems = [[self.MainToolbar items] mutableCopy];
        [barItems removeObjectAtIndex:0];
        [self.MainToolbar setItems:barItems];
    }

This did not work until I added the commented line self.SortButton = nil. Can someone explain that? I thought that if I removed the _sortButton from the array, that it would be uninitialized, but I guess that is wrong. It seems to still have its reference in memory unless you set it to nil. Is that the correct? Thanks.

This is the classic dangling pointer problem.

If you do not null out a pointer, it is still pointing to an address in memory that may or may not actually contain what you want unless you make sure that for the lifetime of the pointer, the object is live.

One thing that I do to help me out in this area is to set all owned pointers to nil when I release them.

Here's a macro that is sure to be handy:

#define RELEASE_NIL(obj) [obj release], obj = nil

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