copy,mutablecopy;property(copy/strong)

一、copy,mutablecopy

1.copy后的值不可改变.NSString/NSArray/NSDictionary。(所以对Mutable赋值最好用mutablecopy)

NSArray*array1 = [NSArrayarrayWithObjects:@"a",@"b",@"c",nil];

NSMutableArray*mArrayCopy1 = [array1 copy];

mArrayCopy1[0]=@"123";//崩溃

2.不可变对象copy是浅拷贝(指针拷贝);地址相同。(其他都是深拷贝)

NSString*string =@"origion";

NSString*stringCopy = [stringcopy];

NSLog(@"string:%p,%@",string,string);//string:0x100003080,origion

NSLog(@"stringCopy:%p,%@",stringCopy,stringCopy);//stringCopy:0x100003080,origion

3.property加copy后,mutableCopy无效;用strong后,直接赋值,两个变量值地址相同,相当于浅拷贝;(所以建议都用strong,需要copy(不跟着改变)的地方用[obj copy])

@property(nonatomic,copy)NSMutableString*cpmtStr;

@property(nonatomic,strong)NSMutableString*stmtStr;

@property(nonatomic,copy)NSMutableString*cpmtStr1;

@property(nonatomic,strong)NSMutableString*stmtStr1;

@property(nonatomic,copy)NSMutableString*cpmtStr2;

@property(nonatomic,strong)NSMutableString*stmtStr2;

------------

NSMutableString*mutStr = [@"123"mutableCopy];

self.cpmtStr= mutStr;//

self.stmtStr= mutStr;

self.cpmtStr1= [mutStrmutableCopy];//mutableCopy无效了,原来已经有了copy了

//[self.cpmtStr1 appendString:@" hello"];//crash,因为mutableCopy

self.stmtStr1= [mutStrmutableCopy];

self.cpmtStr2= [mutStrcopy];//

self.stmtStr2= [mutStrcopy];//

NSLog(@"mutStr:%p,%@",mutStr,mutStr);//mutStr:0x1001028a0,123

NSLog(@"cpmtStr:%p,%@",self.cpmtStr,self.cpmtStr);//cpmtStr:0x33323135,123

NSLog(@"stmtStr:%p,%@",self.stmtStr,self.stmtStr);//stmtStr:0x1001028a0,123

NSLog(@"cpmtStr1:%p,%@",self.cpmtStr1,self.cpmtStr1);//cpmtStr1:0x33323135,123

NSLog(@"stmtStr1:%p,%@",self.stmtStr1,self.stmtStr1);//stmtStr1:0x100102fd0,123

NSLog(@"cpmtStr2:%p,%@",self.cpmtStr2,self.cpmtStr2);//cpmtStr2:0x33323135,123

NSLog(@"stmtStr2:%p,%@",self.stmtStr2,self.stmtStr2);//stmtStr2:0x33323135,123

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容