基本法则:
- You own any object you create
You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example,
alloc
,newObject
, ormutableCopy
).你用alloc, new, copy或者mutableCopy消息创建出来的对象,所有权归你。
- You can take ownership of an object using retain
A received object is normally guaranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. You use
retain
in two situations: (1) In the implementation of an accessor method or aninit
method, to take ownership of an object you want to store as a property value; and (2) To prevent an object from being invalidated as a side-effect of some other operation.你可以使用retain消息来获得对象的所有权。
- When you no longer need it, you must relinquish ownership of an object you own
You relinquish ownership of an object by sending it a
release
message or anautorelease
message. In Cocoa terminology, relinquishing ownership of an object is therefore typically referred to as “releasing” an object.对于你拥有所有权的对象啊,一旦你不需要了,就必须发送release消息或者发送autorelease消息。
- You must not relinquish ownership of an object you do not own
对于你没有所有权的对象,禁止乱发release或者autorelease消息。
实用方法:
-
Use Accessor Methods to Make Memory Management Easier
Don’t Use Accessor Methods in Initializer Methods and dealloc
使用accessor来简化内存管理,但是不要在init和dealloc中调用accessor以避免一些bug产生。具体原因参见这里。 -
Use Weak References to Avoid Retain Cycles
使用弱引用来防止相互依赖。 -
Avoid Causing Deallocation of Objects You’re Using
不要销毁正在使用的对象。 -
Don’t Use dealloc to Manage Scarce Resources
不要使用dealloc来管理稀有资源。 -
Collections Own the Objects They Contain
集合对象拥有其中包含的对象的所有权。 -
Ownership Policy Is Implemented Using Retain Counts
所有权策略是由retainCount实现的。
AutoRelease pool:
一个对象可以被多次调用autorelease,这样在pool drain的时候也会被多次调用release。
每个线程中有一个自动释放池的堆栈。对象的autorelease消息将此对象加入堆栈顶部的pool中。
直接释放非堆栈顶部的pool时,会将其上的所有pool都做一遍drain操作。以保证其中所有对象被释放。这样的机制和异常配合不会有问题。