将指针设置为nil,objective-c [英] Setting pointers to nil, objective-c

查看:89
本文介绍了将指针设置为nil,objective-c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对指针存储器是编程的新手感到有些困惑.因此,我根据选择了UITabBarController的时间来添加UIBarButtonItem,如下所示:

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];
    }

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

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];
    }

直到我添加了注释行self.SortButton = nil,这才起作用.有人可以解释吗?我以为如果我从数组中删除_sortButton,它将被未初始化,但是我想那是错误的.除非将其设置为nil,否则它似乎仍在内存中具有其引用.正确吗?谢谢.

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.

推荐答案

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

如果您不将指针归零,它仍会指向指向内存中的一个地址,该地址实际上可能包含或不包含您想要的内容,除非您确保在指针的生存期内,该对象是活动的.

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.

在该方面可以帮助我的一件事是在释放它们时将所有拥有的指针设置为nil.

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

这篇关于将指针设置为nil,objective-c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆