iOS NSString,NSArray,NSDictionary属性关键字copy

创建了Person类,里面声明个name属性,关键字用copy

@property (nonatomic, copy)NSString *name;

在ViewController里给name赋值

NSMutableString *str = [[NSMutableString alloc] initWithString:@"iPhone"];

Person *person = [[Person alloc]init];

person.name = str;

[str appendString:@"6"];

NSLog(@"\n%@\n%@", str, person.name);

NSLog(@"\n%p\n%p", str, person.name);

打印结果

//iphone6   iphone   copy
//iphone6   iphone6  strong
//0x600001f8c030  //0xd5a5b31a6478d3f4  copy
//0x60000310ea90  //0x60000310ea90      strong
如果strong来修饰,如果NSMutableString的值赋值给NSString,那么只是将NSString指向了NSMutableString的内存地址,并对NSMUtbaleString计数器加一,此时,如果对NSMutableString进行修改,也会导致NSString的值修改,person的name属性会随着str的改变而改变,(试想一下一个人的名字怎么能在不知情的情况下被被改变那),破坏了封装性,原则上这是不允许的.如果是copy修饰的NSString对象,在用NSMutableString给他赋值时,会进行深拷贝,及把内容也给拷贝了一份,两者指向不同的位置,即使改变了NSMutableString的值,NSString的值也不会改变.所以用copy是为了安全,防止NSMutableString赋值给NSString时,前者修改引起后者值变化而用的.
以上规则不止适用于NSString,NSArray,NSDictionary等同理
//NSArray
NSMutableArray *arr = [[NSMutableArray alloc] initWithArray:@[@"iphone6",@"iphone8"]];
    Person *p = [[Person alloc] init];
    p.arr = arr;
    [arr addObject:@"iphone x"];
    DLog(@"\n%@\n%@",arr,p.arr);
    /*
     (
     iphone6,
     iphone8,                    copy (arr)
     "iphone x"
     )
     (
     iphone6,                     copy(p.arr)
     iphone8
     )
     
     strong
     (
     iphone6,
     iphone8,
     "iphone x"
     )
     (
     iphone6,
     iphone8,
     "iphone x"
     )
     
     */
    DLog(@"\n%p\n%p",arr,p.arr);
    //copy   0x60000085d1d0       0x60000066d500
    //strong    0x600001ba84b0     0x600001ba84b0
 
NSDictionary
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"iphone6",@"key1",@"iphone7",@"key2", nil];
    Person *p = [[Person alloc] init];
    p.dict = dict;
    [dict addEntriesFromDictionary:@{@"key3":@"iphone8"}];
    DLog(@"\n%@\n%@",dict,p.dict);
    DLog(@"\n%p\n%p",dict,p.dict);
    /*
     copy
     {
     key1 = iphone6;
     key2 = iphone7;
     key3 = iphone8;
     }
     {
     key1 = iphone6;
     key2 = iphone7;
     }
     
     0x600003436800
     0x600003437700
     */
    /*
     strong
     {
     key1 = iphone6;
     key2 = iphone7;
     key3 = iphone8;
     }
     {
     key1 = iphone6;
     key2 = iphone7;
     key3 = iphone8;
     }
     0x60000276ee60
     0x60000276ee60
     */
 

iOS NSString,NSArray,NSDictionary属性关键字copy

上一篇:查找android so文件中绕过c/c++ api直接调用SYSCALL的方法位置


下一篇:虚拟环境之virtualenvwrapper