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

來源:互聯網
上載者:User

覺得講的很容易理解 

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 用來修飾一個函數的參數,這個參數會在函數返回的時候被自動釋放。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.