iOS 关于@property 中copy的使用

总结:用strong修饰的字符串,当NSMutableString的字符串给他赋值时,NSMutableString的字符串变了,它也会跟着改变,因为stong只是指针的引用(修饰的属性指向赋值对象地址),引用计数加1。

用copy修饰的字符串,不会随着源头的改变而改变,因为copy会复制一份(重新开辟一块新的内存地址),且该属性为不可变对象。

如果源头的字符串是不可变的,那么用copy和strong是一样的,因为源头是不可变的字符串嘛,所以用copy还是strong看你的需要了,想让他随着源头改变就用strong,不想改变有用copy,一般不会让它改变,所以安全起见,字符串会用copy,数组和字典同理

@interface ViewController ()
@property(nonatomic,strong) NSString *nameStrong;
@property(nonatomic,copy) NSString *nameCopy;
@property(nonatomic,strong) NSArray *arrStrong;
@property(nonatomic,copy) NSArray *arrCopy;
@end

@implementation ViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	NSMutableString *muStr = [NSMutableString stringWithString:@"zhangsan"];
    self.nameCopy = muStr ;
    self.nameStrong = muStr;

	NSLog(@"%p",muStr);
	NSLog(@"%p",self.nameStrong);
	NSLog(@"%p",self.nameCopy);
	
	NSLog(@"可变字符串修改前nameStrong= %@ nameCopy=%@",self.nameStrong,self.nameCopy);
	[muStr appendString:@"feng"];
    NSLog(@"可变字符串修改后nameStrong= %@ nameCopy=%@",self.nameStrong,self.nameCopy);
    
    NSArray *aa = @[@"123",@"123"];
    NSMutableArray *muArr = [NSMutableArray arrayWithObject:aa];
    self.arrCopy = muArr ;
    self.arrStrong = muArr;
    NSLog(@"可变数组修改前arrStrong= %@ arrCopy=%@",self.arrStrong,self.arrCopy);
    [muArr addObject:@"123"];
    NSLog(@"可变数组修改后arrStrong= %@ arrCopy=%@",self.arrStrong,self.arrCopy);

@end

你可能感兴趣的:(iOS)