我对指针内存是编程新手有点困惑。所以我添加一个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];
}
我尝试通过检查_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];
}
直到我添加注释行self.SortButton = nil才行。有人可以解释一下吗?我认为如果我从数组中删除了_sortButton,它将是未初始化的,但我想这是错误的。除非你把它设置为nil,它似乎仍然在内存中有它的引用。那是对的吗?感谢。
答案 0 :(得分:10)
这是典型的dangling pointer问题。
如果你没有指出一个指针,那么它仍然指向到内存中的一个地址,除非你确保指针的生命周期,否则实际上可能包含或不包含你想要的内容。对象是实时的。
我在这方面做的一件事就是在发布时将所有拥有的指针设置为nil
。
这是一个确定方便的宏:
#define RELEASE_NIL(obj) [obj release], obj = nil