什么時候使用Strong與copy一直分不清笋熬,其實這個和淺拷貝和深拷貝有關系。參考:參考罩引,文章中有一點不足茸苇,稍后會做補充排苍。
當對NSString進行strong 與copy 時,會有什么不同呢:
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic,strong)NSString *strongString;
@property(nonatomic,copy)NSString *copyedString;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self test];
}
-(void)test{
NSString *string =[NSString stringWithFormat:@"abcshshsrhjrshsrjhsrhjs"];
self.strongString = string;
self.copyedString = string;
NSLog(@"%lu",[string retainCount]);
NSLog(@"orign string:%p,%p",string,&string);
NSLog(@"strong string:%p,%p",_strongString,&_strongString);
NSLog(@"copy string:%p,%p",_copyedString,&_copyedString);
}
打印截圖如下:
可以很直觀的看到学密,引用計數為3 淘衙,strong和copy后指針指向的地址是相同的,所以說對NSString進行操作時腻暮,strong與copy都是對字符串進行了淺拷貝彤守,只是拷貝了指針指向。(補充下參考文章中沒有指明的一點哭靖,親測, 當format后面的字符串長度大于等于12時, 引用計數為1. 這個現象存在于initWithFormat:和stringWithFormat:方法, 至于有沒有其他方法也會有這種情況不敢確定具垫,當只有很少的字符時,引用計數為-1试幽,有興趣的可以測試下筝蚕,只是對文章中進行補充)
對不可變字符串進行strong與copy時會有什么不同呢
修改一行代碼:
NSMutableString *string =[NSMutableString stringWithFormat:@"agagagagagagaegagaga"];
self.strongString = string;
self.copyedString = string;
NSLog(@"%lu",[string retainCount]);
NSLog(@"%lu",[_strongString retainCount]);
NSLog(@"%lu",[_copyedString retainCount]);
NSLog(@"orign string:%p,%p",string,&string);
NSLog(@"strong string:%p,%p",_strongString,&_strongString);
NSLog(@"copy string:%p,%p",_copyedString,&_copyedString);
可以很明顯的看到string 與_strongString的引用計數為2,_copyString的引用計數為1铺坞,string 與_strongString的地址是相同的起宽,而_copyString指向的新的地址,所以對于可變字符串济榨,strong使用了淺拷貝坯沪,copy使用了深拷貝