美文网首页iOS精品文章
iOS 对self.与_ 及copy属性与strong属性的理解

iOS 对self.与_ 及copy属性与strong属性的理解

作者: 菊上一枝梅 | 来源:发表于2018-05-09 11:39 被阅读208次
    • self.与的区别:众所周知在使用self.时,会调用属性的set与get方法;在使用时则不会调用。因为在使用_调用时实则是调用的类的成员变量,而使用self.时则是调用类的属性,使用self.可以访问父类中的的属性。
    • 在学习copy属性与strong属性的时候对self.与_有了更深刻的理解,在此记录一下,如有错误欢迎指正。
    • copy为深拷贝,会将对象的指针及内容一起拷贝出来,说白了就是重新分配一块内存地址,将原来内存中存的数据复制一份放到新内存中,两套数据互不影响;
    • strong为浅拷贝,会将新对象的指针指向原对象的内存地址,两个对象共享一块内存地址,使用相同数据。
    • 为什么将self.与_,还有copy strong属性放在一起说呢,下面用代码说明一下。
    // 属性声明
    @property(nonatomic, copy)NSString *str_copy_self;
    @property(nonatomic, copy)NSString *str_copy_;
    @property(nonatomic, strong)NSString *str_strong_self;
    @property(nonatomic, strong)NSString *str_strong_;
    
    // 测试方法
            NSMutableString *mStr1 = [[NSMutableString alloc] initWithString:@"你好"];
            self.str_copy_self = mStr1;
            _str_copy_ = mStr1;
            self.str_strong_self = mStr1;
            _str_strong_ = mStr1;
            NSLog(@"\n%p -- %@  使用copy属性self.调用的\n%p -- %@  使用copy属性_调用的\n%p -- %@  使用strong属性self.调用的\n%p -- %@  使用strong属性_调用的", self.str_copy_self, self.str_copy_self, _str_copy_, _str_copy_, self.str_strong_self, self.str_strong_self, _str_strong_, _str_strong_);
            [mStr1 appendString:@"吗"];
            NSLog(@"改变值后");
            NSLog(@"\n%p -- %@  使用copy属性self.调用的\n%p -- %@  使用copy属性_调用的\n%p -- %@  使用strong属性self.调用的\n%p -- %@  使用strong属性_调用的", self.str_copy_self, self.str_copy_self, _str_copy_, _str_copy_, self.str_strong_self, self.str_strong_self, _str_strong_, _str_strong_);
    
    • 输出结果


      屏幕快照 2018-05-09 上午11.36.29.png
    • 可以看到,当属性copy属性时,需要用self.调用属性才会对对象进行深拷贝,其它情况始终是指针指向相同的内存地址。
    • 在此记录这次学习,避免以后做项目时遇到这种莫名其妙的问题而迷茫。

    相关文章

      网友评论

      • xxttw:用指针的情况下,strong和copy没区别了
        菊上一枝梅:@Unc1eWang 是呗 使用复制的情况还是比较少的 经常会看到以前的老代码有些用strong修饰的 但是程序运行起来并没什么问题

      本文标题:iOS 对self.与_ 及copy属性与strong属性的理解

      本文链接:https://www.haomeiwen.com/subject/xvjnrftx.html