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

分类:IOS    发布时间:2011/2/28 14:48:00

在<<Learn Objective-C on the Mac>> 172 页,对 Objective-C 的内存管理做了以下说明:

  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.

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

创建对象

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

下面是一些小知识点:

  1. 当你想暂时保留对象时,使用 autolease
        - (Money *)showMeTheMoney:(double)amount {
          Money *theMoney = [[Money alloc] init:amount];
          [theMoney autorelease];
          return theMoney;
        }
  2. 集合类的 autolease,一种方法是像对象一样调用 autolease,另外也可以调用 [NSMutableArray array],最好的方式 return [NSArray arrayWithObjects:@“Steve”, @“Ankush”, @“Sean”, nil];,其他类似的方法返回的对象都是 autolease 的对象。
        [NSString stringWithFormat:@“Meaning of %@ is %d”, @“life”, 42];
        [NSDictionary dictionaryWithObjectsAndKeys:ankush, @“TA”, janestudent, @“Student”, nil];
        [NSArray arrayWithContentsOfFile:(NSString *)path];
  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 定义的

最新评论

我要发表评论

名称:
电子邮件:
个人主页:
内容:

 博客分类