zoukankan      html  css  js  c++  java
  • 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,才能拷贝。

        

     

     

  • 相关阅读:
    Google Map API使用详解(一)——Google Map开发背景知识
    IOS开发中发送Email的两种方法
    iOS简单的画线(UIImageVIew方式)
    NSData + Base64
    (转载)谈Flash的破解与加密(附flash破解工具)
    Google Map API使用详解(二)——Google Map API中文说明
    oracle sysdate 等 时间的相关应用
    vc mail 封装类
    switch if 比较
    http://tech.ddvip.com/200810/122362552676322.html state模式~
  • 原文地址:https://www.cnblogs.com/dashengios/p/10375073.html
Copyright © 2011-2022 走看看