Objective-C内存管理的几点总结

如果你对Objective-C已经很了解,那么复习下内存 管理的规则吧:

在<<Learn Objective-C on the Mac>> p.172上提到

   1. 当你使用new,alloc或copy创建对象时,对象的count retain到1。你一定要负责把这个对象release 或 autolease掉。这样当它的生命周期结束时,它才能清空。When you create an object using new, alloc, or copy, the object has a retain count of 1. You are responsible for sending the object a release or autorelease message when you’re done with it. That way, it gets cleaned up when its useful life is over.
   2. 当你使用 其他方法获得一个对象时,你可以认为它已经retain了一个count,并且autolease掉了。你不用考虑和它相关的清理问题 。但是如果你想保留这个对象,那么你需要retain它,并且要确保之后你release了这个对象。When you get hold of an object via any other mechanism, assume it has a retain count of 1 and that it has already been autoreleased. You don’t need to do any fur- ther work to make sure it gets cleaned up. If you’re going to hang on to the object for any length of time, retain it and make sure to release it when you’re done.
   3. 如果你retain一个对象,你最终总是需要release或者autolease它。If you retain an object, you need to (eventually) release or autorelease it. Balance these retains and releases.

这三条规则在写代码 的时候一定要遵守,一旦遵守了一般也就不会有内存泄露的问题。


创建对象

ObjectiveC 中创建对象分为alloc和init两步,alloc是在堆(heap)上初始化内存给对象变量,把变量(指针)设为nil。每个类可以很多init方法,且每个方法都以init开头,但每个类只有一个特定(designated)的init方法,NSObject是init;,UIView是- (id)initWithFrame:(CGRect)aRect;。在子类的designated方法中一定要调用父类的designated方法,子类其他的init方法只能调用子类自己的designated方法,不能调用父类的(即使用self而不是super)。


Reference Counting(引用计数)

ObjectvieC的内存管理机制,略。


下面是一些小知识点:


1. 当你想暂时保留对象时,使用autolease

 


2. 集合类的autolease,一种方法是像对象一样调用autolease,另外也可以调用[NSMutableArray array],最好的方式 return [NSArray arrayWithObjects:@“Steve”, @“Ankush”, @“Sean”, nil];,其他类似的方法返回的对象都是autolease的对象

 

 

 

 

3. 集合类对新增的对象拥有ownership
4. @"string"是autorelease的
5. NSString一般是copye而不是retain
6. 你应该尽快release你拥有的对象,越快越好。建议创建完对象后就写好release的代码。
7. 当最后一个对象owner release后,会自动 调用dealloc函数,在类中需要重载dealloc,但永远都不要自己去调用dealloc
8. @property一般直接返回对象变量,我们可以把它理解为返回的是autolease的对象。
9. 使用@synthesize实现时,@property可以指定setter函数使用retain,copy或assign。assign一般用在属性一定会随着对象的消亡而消亡的,比如controller的view,view的delegate。
10. Protocols可以理解为抽象接口,delegat和dataSource基本都是用protocol定义的。

 


转自:http://www.cocoachina.com/bbs/read.php?tid-48322.html

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值