`
java-mans
  • 浏览: 11435177 次
文章分类
社区版块
存档分类
最新评论

IOS内存释放规则

 
阅读更多
  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 定义的

1. 通过分配或复制创建的对象保持计数1
2. 假设任何别的方法获取的对象保持计数1,而且在自动释放池中. 要想在当前执行范围外使用该对象,就必须保持它
3. 向集合添加对象时它就被保持,从集合移除对象时就被释放.释放集合对象会释放该集合中的所有对象
4. 确保有多少alloc,copy,mutableCopy或retain消息就有多少release或autorelease消息发送给该对象. 换句话说,确保你的代码平衡
5. 在访问方法设置属性,先保持,再释放 (ztime: 现在有@propperty , @synthesize 两个指令自动创建此代码)
6. 用@"..."结构创建的NSString对象是常量.发送release或retain并无效果

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics