【IOS之内存管理】什么时候应该使用retain

来源:互联网 发布:利润率的算法 编辑:程序博客网 时间:2024/05/16 15:30

官方例子中的代码,
UIButton *infoButton = [[UIButton buttonWithType:UIButtonTypeInfoLight] retain];

为什么不写成
    UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight] ;

两者有什么差别?

补充,这段代码是写在UIView子类的initWithFrame方法里

- (id)initWithFrame:(CGRect)frame viewController:(LevelViewController *)aController {
    self = [super initWithFrame:frame];
    if (self != nil) {
     UIButton *infoButton = [[UIButton buttonWithType:UIButtonTypeInfoLight] retain];
     ……………………
    }
    return self;

}

疑问:infoButton是一个局部变量,只出现在initWithFrame方法里,其他没有要用到的地方。
这样写,是不是一个习惯问题。



回答一
UIButton *infoButton = [[UIButton buttonWithType:UIButtonTypeInfoLight] retain];

retain一下计数加1,表示我的代码需要使用这个infoButton,可能在其它地方会使用,使用完了手动release一下

目的在于避免系统autorelease掉这个button

回答二
buttonWithType是类方法,它创建的对象系统会自动释放的。
所以应该retain保持一下,等这个对象使用完了,再release就可以。 


问题

仔细想了想,还有疑惑的地方。infoButton初始化的时候,不使用retain,也可以啊,
它是类方法创建的,被标记为autorelease,是不是程序结束的时候,才释放pool中的变量(就是里面的变量执行一次release。)
如果是这样,一直到程序运行结束前,也没有任何release infoButton的地方,所以retain一下,是不是真的多余里呢?

为什么执行到列表的 numberOfRowsInSection方法,数据的retain count就少了1?

0 0
原创粉丝点击