将指针设置为nil,objective-c

Cry*_*tal 2 iphone memory-management objective-c ios

关于指针内存是编程的新手,我有点困惑.所以我添加一个UIBarButtonItem基于何时选择UITabBarController,如下所示:

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];
    }
Run Code Online (Sandbox Code Playgroud)

我尝试通过检查_sortButton是否为n来删除UIBarButton:

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

直到我添加注释行self.SortButton = nil才行.有人可以解释一下吗?我认为如果我从数组中删除了_sortButton,它将是未初始化的,但我想这是错误的.除非你把它设置为nil,它似乎仍然在内存中有它的引用.那是对的吗?谢谢.

Jac*_*kin 10

这是经典的悬空指针问题.

如果你没有指出一个指针,它仍然指向内存中的一个地址,除非你确保在指针的生命周期内,该对象是实时的,否则它实际上可能包含你想要的内容.

我在这个领域帮助我的一件事是nil在释放它们时设置所有拥有的指针.

这是一个确定方便的宏:

#define RELEASE_NIL(obj) [obj release], obj = nil
Run Code Online (Sandbox Code Playgroud)

  • 这可能是有用的有条件地定义这个宏`#定义RELEASE_NIL(OBJ)OBJ发布],OBJ =(ID)0x42`在调试版本中你调试,而不是沉默的故障期间获得硬碰撞,这在无价捡到虫子. (5认同)