為什么NSSTring對象用copy修飾

相信有很多人都有這個疑惑,為什么NSString對象用copy修飾?其實NSString也是可以用strong修飾的但是最好還是選擇copy,為啥呢 ?請看下面的解釋
copy的意思是對值進行拷貝,分為淺拷貝與深拷貝,深拷貝會產(chǎn)生一個新對象;
strong是強引用,對象指針指向的是同一個,不會產(chǎn)生新對象;
我們先來看一個例子

@property (nonatomic, strong) NSMutableString *strStrong;
@property(nonatomic, copy) NSmutableString *strCopy;
NSMutableString *name = [[NSMutableString alloc] initWithString: @"hello"];
self.strStrong = name;
self.strCopy = name;
//1.此時給name拼接一個字符
[name appendString: @"word"];
NSLog(@"%@ %p", name, name);
NSLog(@"%@ %p", self.strStrong, self.strStrong);
NSLog(@"%@ %p", self.strCopy, self.strCopy);
結(jié)果為:
helloword 0x6000002495d0
helloword 0x6000002495d0
hello     0xa00006f6c6c65685

2.給self.strStrong拼接一個字符
[self.strStrong appendString: @"!?。?!"];
NSLog(@"%@ %p", name, name);
NSLog(@"%@ %p", strStrong, strStrong);
NSLog(@"%@ %p", strCopy, strCopy);
結(jié)果為:
helloword?。。?! 0x60400025d790
helloword?。。?! 0x60400025d790
hello            0xa00006f6c6c65685

可以看出,用strong修飾的屬性strStrong,隨著name值的變化,也跟著變化,然而copy修飾的值就沒有發(fā)生變化,更加安全。
使用copy,主要是為了防止當NSMutableString賦值給NSString時,兩者之一變化,都會引起另外一個值變化。

下面講一下深拷貝與淺拷貝

    NSString *copy = @"apple";
    NSString *copyString1 = [copy copy];//原對象
    NSString *copyMuStr1 = [copy mutableCopy];//產(chǎn)生新的對象
    NSLog(@"%p %p %p", copy, copyString1, copyMuStr1);
    //0x1034c2118 0x1034c2118 0x60400025f5c0
    
    NSMutableString *mutabStr = [NSMutableString stringWithString:@"watermelon"];
    NSString *copyStr2 = [mutabStr copy];//產(chǎn)生新的對象
    NSString *copyMuStr2 = [mutabStr mutableCopy];//產(chǎn)生新的對象
    NSLog(@"%p %p %p", mutabStr, copyStr2, copyMuStr2);
    //0x600000247800 0x60000003fd40 0x600000247530
AAC3A81E1115A66FBDAA1966DD89CE89.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容