您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 開發中 Strong 與 Weak 的深入理解

編輯:iOS 相關資訊

這段講解非常容易理解。

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.

 

用中文來說就是:strong 和 weak 不同的是,當一個對象不再有 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 用來修飾一個函數的參數,這個參數會在函數返回的時候被自動釋放。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved