Setting pointers to nil, objective-c

佐手、 提交于 2019-12-24 05:04:05

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/6823394/setting-pointers-to-nil-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!