在@property
中存在copy
、strong
修饰符,不存在mutableCopy
对于可变对象属性 (NSMutableString
、NSMutableDictionary
、NSMutableArray
) 与 不可变对象属性 (NSString
、NSDictionary
、NSArray
)而言
修饰不可变的对象属性用copy,修饰可变的对象属性用strong
先看一下代码:
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic, strong) NSMutableString *strMutStrong;
@property(nonatomic, copy) NSMutableString *strMutCopy;
@property(nonatomic, copy) NSString *strCopy;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableString *strM = [NSMutableString stringWithString:@"strM"];
self.strCopy = strM;
self.strMutStrong = strM;
self.strMutCopy = strM;
[strM appendString:@"str"];
NSLog(@"%@---%p", strM, strM); // 内容:strMstr 加入地址是:0x010
NSLog(@"strCopy:%@---%p", self.strCopy, self.strCopy); // strM 0x011
NSLog(@"strMutStrong:%@---%p", self.strMutStrong, self.strMutStrong); // strMstr 0x010
NSLog(@"strMutCopy:%@---%p", self.strMutCopy, self.strMutCopy); // strM 0x011
}
打印结果截图:

解释如下:
1、对于
NSString
用Copy
修饰的时候,其实就是在setter
方法内部默认实现了copy方法,从可变到不可变进行copy
属于深拷贝,指针和内存全部复制一份,内容不变,内存地址发生变化。改变之前的strM
变量内容也不会影响到strCopy
的内容,安全。2、对于
NSMutableString
用strong
修饰时候,只是多了一个指针指向原本的对象,内容与地址始终保持是一直的。3、对于
NSMutableString
用copy
修饰的时候,strMutCopy
的setter
方法内部也会有copy
方法调用,strMutCopy
已经是一个不可变的对象属性,与strCopy
相同地址与内容
分别打印class
如下所示:

由截图可知:
strM
与self.strMutStrong
是__NSCFString
可变self.strCopy
与self.strMutCopy
是NSTaggedPointerString
不可变,如果调用appendString:
程序会crash
参考__NSCFString \NSTaggedPointerString部分解析
深拷贝浅拷贝
网友评论