概念:
淺拷貝:不拷貝對象,只拷貝對象指針,因此不會產(chǎn)生新的對象。
深拷貝:拷貝對象到新的內(nèi)存,因此會產(chǎn)生新的對象。
示例:
NSString *string = [[NSString alloc] init];
NSString *s1 = [string copy];
NSString *s2 = [string mutableCopy];
NSLog(@"string==%p, s1--%p, s2==%p", string, s1, s2);
結(jié)果:string==0x100fa6320, s1--0x100fa6320, s2==0x604000257b80
NSMutableString *str = [[NSMutableString alloc] init];
NSMutableString *str1 = [str copy];
NSMutableString *str2 = [str mutableCopy];
NSLog(@"str--%p, str1--%p, str2==%p", str, str1, str2);
結(jié)果: str--0x604000258060, str1--0x101eb0030, str2==0x604000258150
結(jié)論 | mutableCopy | copy |
---|---|---|
可變對象 | 深拷貝 | 深拷貝 |
不可變對象 | 深拷貝 | 淺拷貝 |
然后我們再來看copy關(guān)鍵字的特點(diǎn):
修改源對象的屬性和行為,不會影響副本對象
修改副本對象的屬性和行為,不會影響源對象