Objective-C中的Strong、Copy與MutableCopy

面試過程當中常常被問到ARC中Strong、Copy的區別是什麼。普通的回答是:同樣。文藝(正確)的回答是:分狀況(我擦!WQY#$&Y**%OWEUR)html

能夠先參考這篇文章http://www.cnblogs.com/lihaiyin/p/4647426.html面試

 

問題一:到底用Copy仍是Strongthis

1. 把不可變對象寫成Copy:   若是把不可變對象賦值給此屬性,內存中其實就是retain了一下。 若是把可變對象賦值給此屬性,會生成新的不可變對象,避免值的變化spa

2. 把不可變對象寫成Strong: 若是把不可變對象賦值給此屬性,內存中其實就是retain了一下。 若是把可變對象賦值給此屬性,會致使賦值後的內容依然可變code

3. 把可變對象寫成Strong:   若是把不可變對象賦值給此屬性,調用此對象的addXX等增、刪的方法時會崩潰。若是把可變對象賦值給此屬性,內存中其實就是retain了一下。htm

4. 把可變對象寫成Copy:     不管是誰賦值給此屬性,都會調用Copy生成不可變對象,都會在調用此對象的addXX等增、刪的方法時會崩潰對象

 

所以,咱們的代碼中通常都會  把不可變對象寫成Copy  把可變對象寫成Strongblog

 

問題二:源碼中的Copy方法爲何copyItem的參數是YES?內存

/**
 * Returns a new copy of the receiver.<br />
 * The default abstract implementation of a copy is to use the
 * -initWithArray:copyItems: method with the flag set to YES.<br />
 * Immutable subclasses generally simply retain and return the receiver.
 */
- (id) copyWithZone: (NSZone*)zone
{
  NSArray    *copy = [NSArrayClass allocWithZone: zone];

  return [copy initWithArray: self copyItems: YES];
}

/**
 * Returns an NSMutableArray instance containing the same objects as
 * the receiver.<br />
 * The default implementation does this by calling the
 * -initWithArray:copyItems: method on a newly created object,
 * and passing it NO to tell it just to retain the items.
 */
- (id) mutableCopyWithZone: (NSZone*)zone
{
  NSMutableArray    *copy = [NSMutableArrayClass allocWithZone: zone];

  return [copy initWithArray: self copyItems: NO];
}

對比一下,發現initWithArray:copyItems方法的參數很怪。都知道,不管NSArray是copy仍是mutableCopy,item都是retain的,不會copy,那爲啥copyWithZone方法(copy方法調用時會調用此方法)的實現中,copyItem的參數是YES?源碼

-initWithArray:copyItems: method with the flag set to YES.<br />
 * Immutable subclasses generally simply retain and return the receiver

想了好久,後來發現,答案就在註釋中,不可變子類(NSString、NSArray、NSDictionary)通常只是簡單的retain。。。對不可變對象調用copy只是retain,對可變對象調用copy會生成不可變對象,因此,爲了使得新生成的NSArray「不可變」(元素自己也要不可變),只能使用copy,但這裏的copy並不是爲item生成了新的對象,只是爲了生成「不可變」的對象

相關文章
相關標籤/搜索