iOS copy 和 mutableCopy 學習
(參考 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]; }
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
參考:
http://ios.jobbole.com/87987/
posted on 2016-08-15 17:14 ACM_Someone like you 閱讀(336) 評論(0) 收藏 舉報
浙公網安備 33010602011771號