汽油降价最新消息:Objective-C内存管理的几点总结 | 1个饼

来源:百度文库 编辑:偶看新闻 时间:2024/04/27 22:50:52

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

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

在<> 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 ? 1 2 3 4 5 - (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的对象 ? 1 2 3 [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定义的。