深拷貝:是指對(duì) 堆中已存在的內(nèi)存空間進(jìn)行的操作抖仅,先開(kāi)辟一塊新的空間(即產(chǎn)生新指針)并將 已存在內(nèi)存空間的 內(nèi)容 進(jìn)行復(fù)制進(jìn)去坊夫;
淺拷貝:是指 指針指向堆中已經(jīng)存在的內(nèi)存空間,將內(nèi)容進(jìn)行復(fù)制撤卢,并不會(huì)開(kāi)辟新的內(nèi)存空間(即不會(huì)產(chǎn)生新指針)环凿;
以下[str retain]的打印結(jié)果困擾了我許久,沒(méi)有想明白放吩,其實(shí)這個(gè)問(wèn)題真的是很簡(jiǎn)單---->retainCount=-1是因?yàn)閟tr為字符串常量智听,系統(tǒng)會(huì)用UINT_MAX來(lái)標(biāo)記,系統(tǒng)不收回渡紫,也不做引用計(jì)數(shù)到推。恍然大悟惕澎,瞬間懵逼了~~~
- (void)viewDidLoad {
[super viewDidLoad];
/********************測(cè)試一********************/
NSMutableArray *ary = [[NSMutableArray array] retain];
NSString *str = [NSString stringWithFormat:@"test"];
NSLog(@"%@ %d",str,[str retainCount]);
[str retain];
[ary addObject:str];
NSLog(@"%@ %d",str,[str retainCount]);
[str retain];
[str release];
[str release];
NSLog(@"%@ %d",str,[str retainCount]);
[ary removeAllObjects];
NSLog(@"%@ %d",str,[str retainCount]);
/********************測(cè)試二********************/
NSString *str1 = [NSString stringWithFormat:@"i"];
NSString *str2 = @"1";
[str2 retain];
NSString *str3 = [NSString stringWithFormat:@"imfais"];
NSLog(@"str1 = %d",[str1 retainCount]); //retaincount = 18446744073709551615
NSLog(@"str2 = %d",[str2 retainCount]);
NSLog(@"str3 = %d",[str3 retainCount]); //retaincount = 1
/********************測(cè)試三********************/
NSString *strTest = @"hello gays??????";
NSString *strRetain = [strTest retain];
NSString *strCopy = [strTest copy];
NSMutableString *strMutCopy = [strTest mutableCopy];
NSLog(@"strTest = %p, retainCount = %d", strTest, [strTest retainCount]);
NSLog(@"strRetain = %p, retainCount = %d", strRetain, [strRetain retainCount]);
NSLog(@"strCopy = %p, retainCount = %d", strCopy, [strCopy retainCount]);
NSLog(@"strMutCopy = %p, retainCount = %d", strMutCopy, [strMutCopy retainCount]);
}
此處的retainCount 均用%d進(jìn)行打印莉测,有的人用%lu會(huì)打一出來(lái)一個(gè)龐大的數(shù)字->18446744073709551615,原因是lu是longInteger唧喉,實(shí)際值是-1.
觀(guān)察打印信息可以發(fā)現(xiàn)悔雹,不管是retain還是copy對(duì)于NSString來(lái)說(shuō)都是淺拷貝,還是指向的之前的內(nèi)存區(qū)域欣喧。
NSString 應(yīng)用 retain 還是 copy?
1梯找。對(duì)NSString應(yīng)用retain,效率無(wú)疑是最好的
2。用copy最安全两芳,因?yàn)镹SString 為 NSMutableString 的基類(lèi)肆氓,如果將NSMutableString 以retain的形式賦值給NSString后,后續(xù)修改NSMutableString會(huì)導(dǎo)致NSString內(nèi)容的變化久免,這通常不是我們希望的浅辙,所以用copy最安全。