天天看點

IOS開發(87)之Strong與Weak的了解

轉:http://stackoverflow.com/questions/9262535/explanation-of-strong-and-weak-storage-in-ios5 

覺得講的很容易了解  

The difference is that an object will be deallocated as soon as there are no strong pointers to it. Even if weak pointers point to it, once the last strong pointer is gone, the object will be deallocated, and all remaining weak pointers will be zeroed out.

Perhaps an example is in order.

Imagine our object is a dog, and that the dog wants to run away (be deallocated).

Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached.

Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it.

As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out.

(weak和strong)不同的是 當一個對象不再有strong類型的指針指向它的時候 它會被釋放  ,即使還有weak型指針指向它。

一旦最後一個strong型指針離去 ,這個對象将被釋放,所有剩餘的weak型指針都将被清除。

可能有個例子形容是妥當的。

想象我們的對象是一條狗,狗想要跑掉(被釋放)。

strong型指針就像是栓住的狗。隻要你用牽繩挂住狗,狗就不會跑掉。如果有5個人牽着一條狗(5個strong型指針指向1個對象),除非5個牽繩都脫落 ,否着狗是不會跑掉的。

weak型指針就像是一個小孩指着狗喊到:“看!一隻狗在那” 隻要狗一直被栓着,小孩就能看到狗,(weak指針)會一直指向它。隻要狗的牽繩脫落,狗就會跑掉,不管有多少小孩在看着它。

隻要最後一個strong型指針不再指向對象,那麼對象就會被釋放,同時所有的weak型指針都将會被清除。

iOS 5 中對屬性的設定新增了strong 和weak關鍵字來修飾屬性(iOS 5 之前不支援ARC)

strong 用來修飾強引用的屬性;

@property (strong) SomeClass * aObject; 

對應原來的 

@property (retain) SomeClass * aObject; 和 @property (copy) SomeClass * aObject; 

weak 用來修飾弱引用的屬性;

@property (weak) SomeClass * aObject; 

對應原來的 

@property (assign) SomeClass * aObject; 

__weak, __strong 用來修飾變量,此外還有 __unsafe_unretained, __autoreleasing 都是用來修飾變量的。

__strong 是預設的關鍵詞。

__weak 聲明了一個可以自動 nil 化的弱引用。

__unsafe_unretained 聲明一個弱應用,但是不會自動nil化,也就是說,如果所指向的記憶體區域被釋放了,這個指針就是一個野指針了。

__autoreleasing 用來修飾一個函數的參數,這個參數會在函數傳回的時候被自動釋放。