NSString为什么经常用copy修饰,用strong会有什么问题?

@interface ViewController ()

 

@property (nonatomic, strong) NSString   *str1;

@property (nonatomic, copy)   NSString   *str2;

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    

    NSMutableString *mtStr = [NSMutableString stringWithFormat:@"hello"];

    

    self.str1 = mtStr;

    self.str2 = mtStr;

    [mtStr appendString:@"world"];

    NSLog(@"mtStr:%p,,str1:%p,, str2:%p",mtStr, self.str1,self.str2);

    NSLog(@"%@-------%@",self.str1, self.str2);

}

打印结果:

2019-02-14 15:09:28.735175+0800 CYLArrayCopyDmo[5109:506346] mtStr:0x281e945a0,,str1:0x281e945a0,, str2:0xa00006f6c6c65685

2019-02-14 15:09:38.204747+0800 CYLArrayCopyDmo[5109:506346] helloworld-------hello

 

使用copy修饰的会重新拷贝一份,是新的内存地址(因为被拷贝的对象是可变的,如果拷贝的对象是不可变的,那么使用copy属性只是指针拷贝,对应的是同一块内存地址)

strong是指针引用,是在原来的地址上进行强引用,值会跟随对象值的变化而变化。

 

另外关于copy与mutableCopy的注意点:

 

  NSString *originStr = @"haha";

    NSString *newStr1 = [originStr copy];

    NSString *newStr2 = [originStr mutableCopy];

 

   NSLog(@"originStr:%p,,newStr1:%p,,newStr2:%p",originStr,newStr1,newStr2);

打印结果:

2019-02-14 15:53:14.392678+0800[5311:515095] originStr:0x100ff80f8,,newStr1:0x100ff80f8,,newStr2:0x282e1c480

注意:如果对象是可变的,不管使用copy还是mutableCopy,都会开辟新的内存空间。 比如: 对mutableString进行copy或者mutableCopy

 

结论:copy与mutableCopy 要看拷贝的对象是不可变的还是可变的,如果拷贝的对象是不可变的, 那么copy只是浅拷贝,不会开辟新的内存,mutableCopy会开辟新的内存。

   如果对象是可变的,那么copy和mutableCopy都会开辟新的内存,都是深拷贝。。

 

   自定义对象的拷贝都是深拷贝。自定义对象必须实现 NSCoping 和NSMutableCoping 协议,并实现copyWithZone或者mutableCopyWithZone,才能拷贝。

    

 

 

原文地址:https://www.cnblogs.com/dashengios/p/10375073.html