什麼是copy?app
顧名思義,就是拷貝,拷貝視頻,拷貝txt,在window下面就是複製,就是生成一個副本文件,和源文件內容如出一轍.atom
字符串的Copy/MutableCopy方法spa
>可變字符串(能夠被修改)的copy.指針
1.假設NSMutableString經過copy以後產生的對象是可變的.code
NSMutableString *str = [NSMutableString stringWithFormat:@"張三"]; NSMutableString *str2 = [str copy]; [str2 appendString:@"與李四"]; NSLog(@"%@",str2);
NSLog(@"%p----%p",str,str2);0x7fb56a470b10----0x7fb56a439af0//副本對象從新分配了內存
報錯:orm
reason: 'Attempt to mutate immutable object with appendString:'
>不可變字符串(不能夠被修改)的copy.視頻
1.假設不可變字符串copy後產生的對象是可變的,那麼能夠用NSMutableString接收,並拼接字符串,對象
NSString *STR = @"小魚兒"; NSMutableString *STR2 = [STR copy]; [STR2 appendString:@"與花完好"]; NSLog(@"%@",STR2);
NSLog(@"%p----%p",str,str2); 0x10bbd3068----0x10bbd3068//並無產生副本對象.
然而,報錯了.blog
reason: 'Attempt to mutate immutable object with appendString:'
說明---NSString經過copy產生的是不可變對象,只能用NSString接收,也是不可變字符串內存
綜上:不管是可變字符串仍是不可變字符串,只要是經過copy方式產生副本對象,這個副本對象都是不能夠改變的.
>字符串的MutableCopy,
>可變字符串的MutableCopy.
>1.假設產生的副本對象是是不可變的
NSMutableString *str = [NSMutableString stringWithFormat:@"志明"]; NSMutableString *str2 = [str mutableCopy]; [str2 appendString:@"與春嬌"]; NSLog(@"%@",str2);
NSLog(@"%p----%p",str,str2); //0x7fdbf948b080----0x7fdbf948b100
輸出:志明與春嬌
說明----可變字符串經過MutableCopy產生的對象是可變的./副本對象從新分配了內存
>不可變字符串的MutableCopy.
>2.假設產生的副本對象是不可變的
NSString *str = @"美女"; NSMutableString *str2 = [str mutableCopy]; [str2 appendString:@"與野獸"]; NSLog(@"%@",str2);
NSLog(@"%p----%p",str,str2);//輸出0x10b5bb068----0x7f8392527e80
輸出:美女與野獸
說明----不可變字符串經過MutableCopy產生的副本對象是可變的.
綜上,只要是經過MutableCopy產生副本對象,無論原對象是否可變,副本對象都是可變的./副本對象從新分配了內存
注意:NSString經過copy並無產生新對象,只是指針(地址)的拷貝.就是說是並無真正產生副本對象.
copy與內存管理
NSString經過copy方式產生的副本對象只是對象地址的拷貝.
NSString *str = [NSString stringWithFormat:@"中"]; NSLog(@"str.retainCount = %lu",str.retainCount);//1 NSString *str2 = [str copy]; NSLog(@"str = %p----str2 = %p",str,str2);//同樣 NSLog(@"str.retainCount = %lu",str.retainCount);//2 NSLog(@"str2.retainCount = %lu",str2.retainCount);//2
NSMutableString經過copy方式產生了真正的副本對象.
有一個person類,有一個name屬性
@property (nonatomic,strong) NSString *name;
NSMutableString *str = [NSMutableString string]; [str appendString:@"張三"]; Person *per = [[Person alloc]init]; per.name = str; [str appendString:@"與李四"]; NSLog(@"p.name = %@",per.name);
輸出:2016-03-21 23:28:01.510 copy[2905:94751] p.name = 張三與李四
由於per.name和str實際上指向同一片內存空間,緣由在於,用strong修飾name,只會致使在賦值後賦值對象,str和被賦值對象引用計數+1,並不會產生不可變的副本對象,修改str以後,per.name所指向的內存空間的值發生了改變,於是也會被修改,故而一般咱們用copy修飾字符串.
若是不但願per.name被修改,那麼在賦值的時候能夠這樣寫:
per.name = str.copy
這樣,就不會致使姓名被修改了.