Objective-C问题记录

1. 《iPhone开发基础教程》P27下半页的代码,buttonPressed函数里面,title为啥不用release?

 

2. 何时会需要在代码中主动调用dealloc?

 

3. 变量都是指针?如果release引用计数到零了,那变量的值是啥?之所以这么问是因为在Learn Objective-C教程 中提到:

 

We can also use this to improve our dealloc method slightly:

 
- (void) dealloc
{
self .caption = nil ;
self .photographer = nil ;
[super dealloc];
}

 

This works because when we set nil as an instance variable, the setter just retains nil (which does nothing) and releases the old value. This approach is often better for dealloc because there's no chance of the variable pointing at random data where an object used to be.

 

4. 考考大家,上面这段代码,为啥非要用self.<var> 的形式,而不是直接caption = nil;呢?

 

5. 关于内存管理,话说实践中需要创建一个object不外两种情况:

a. To keep it as an instance variable
b. To use temporarily for single use inside a function

情况a,一般有个setter,setter会释放旧的,retain新的,所以只要在dealloc里release即可;

情况b,在函数中临时用一下,有个简单原则,if you create an object with alloc or copy , send it a release or autorelease message at the end of the function. If you create an object any other way, do nothing.

例子:

NSNumber* value1 = [[NSNumber alloc ] initWithFloat:8.75];

NSNumber* value2 = [NSNumber numberWithFloat :14.78];

// only release value1, not value2

[value1 release ];

这个原则似乎解释了上面问题1,至于其原理,暂时不要问我。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值