iOS copy 和 mutableCopy 學習

來源:互聯網
上載者:User

標籤:

(參考 iOS 52個技巧學習心得筆記 第二章 對象 , 訊息, 運行期)的對象部分

關於Copy  有個經典問題”大部分的時候NSString的屬性都是copy,那copy與strong的情況下到底有什麼區別呢” 或者說”為什麼 NSString 類型成員變數的修飾屬性用 copy 而不是 strong (或 retain ) ?”

明顯 第一句比第二句 嚴謹多了.

@property (strong,nonatomic) NSString *strongString; & @property (copy,nonatomic) NSString *copyString;

正確理解 應該是區分這兩種表達方式的區別

不同寫法,許可權 不同 安全層級不同.

(1)如果是 一個 普通NSString 賦值給copyString 和 strongString  沒區別,  copy 是淺拷貝, 對於二者的被賦值 都是指標引用

(2)如果是一個可變字串NSMutableString 賦給copyString 和 strongString ,對於copyString則是深複製 不會跟著源頭的變化而變化.而strongString 還是淺複製 是指標引用 會隨著源頭的變化而變化

 

其二,copy 和 mutableCopy

copy 是淺複製 , 簡單指標引用,隨源頭的變化而變化 

multableCopy 是深複製,是建立了一個新的對象,不會隨著源頭變化而變化

以下 是一位網友得到的 的Runtime源碼中NSMutableString.m執行個體方法-(id)copy {    return [[NSString alloc] initWithString:self];}
  -(id)copyWithZone:(NSZone*)zone {
    return [[NSString allocWithZone:zone] initWithString:self];
}
對於 NSObject.mm方法- (id)copy {    return [(id)self copyWithZone:nil];}- (id)mutableCopy {    return [(id)self mutableCopyWithZone:nil];}NSString.m調用- (id)copyWithZone:(NSZone *)zone {   if (NSStringClass == Nil)        NSStringClass = [NSString class];    return RETAIN(self); }- (id)mutableCopyWithZone:(NSZone*)zone {    return [[NSMutableString allocWithZone:zone] initWithString:self];}

由此可見 在可變類型中 copy也是深複製,但是類型變成了 普通類型,不能再增加或者減少集合元素了 

在普通類型中 使用mutableCopy 也是深複製,類型變成了 可變類型...

 

NSString *haha = @"hahahhahahah";NSLog(@"%p\n%p",haha,[haha mutableCopy]);

2016-08-15 17:42:09.843 dailylife[69904:5024325] 0x10f6fa390

0x7f8079c41f80

Printing description of haha:

hahahhahahah

Printing description of haha:

hahahhahahah

Printing description of haha:

(NSMutableString) NSMutableString = {

  NSString = {

    NSObject = {

      isa = __NSCFConstantString

    }

  }

}

 

 

 

同理:NSString  NSArray NSDictionary  

 

 

參考:

https://searchcode.com/file/68838008/jni%20w:%20itoa%20runtime%20and%20allocator/Foundation/NSMutableString.m

http://ios.jobbole.com/87987/

 

iOS copy 和 mutableCopy 學習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.