美文网首页程序员
OC中 copy 与 strong

OC中 copy 与 strong

作者: DSA碼侬 | 来源:发表于2018-04-03 11:36 被阅读54次

@property中存在copystrong修饰符,不存在mutableCopy
对于可变对象属性 (NSMutableStringNSMutableDictionaryNSMutableArray) 与 不可变对象属性 (NSStringNSDictionaryNSArray)而言

修饰不可变的对象属性用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    
}

打印结果截图:

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

分别打印class如下所示:

class.png
由截图可知:
strMself.strMutStrong__NSCFString可变
self.strCopyself.strMutCopyNSTaggedPointerString不可变,如果调用appendString:程序会crash
参考__NSCFString \NSTaggedPointerString部分解析
深拷贝浅拷贝

相关文章

网友评论

    本文标题:OC中 copy 与 strong

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