OC NSDictionary的属性一般为什么要设置为copy

我们通过代码来说明:

//一个VC的Interface()中,一般情况下我们这样声明的属性关键字
@property (nonatomic, copy) NSDictionary *dict;// copy
@property (nonatomic, strong) NSMutableDictionary *dictM;

//做个简单的测验,-viewDidload中
self.dict = @{@"firstName": @"Wong",
                       @"secondName": @"Jarvis"};
self.dictM = [@{@"firstName": @"Song",
                               @"secondName": @"Harvis"} mutableCopy];
self.dict = self.dictM;//这里我们做了赋值,可变字典的值赋给了不可变字典
NSLog(@"dict : %@", self.dict);
NSLog(@"dict : %@", self.dictM);

[self.dictM setObject:@"Marvis" forKey:@"secondName"];//修改可变字典中的一个secondName对应值
NSLog(@"dict : %@", self.dict);
NSLog(@"dict : %@", self.dictM);

看看打印结果

//前两个log输出发现可变字典赋值给不可变字典之后,二者的值相同
2020-05-07 16:06:47.214867+0800 ThirdLibPro[21019:303026] dict : {
    firstName = Song;
    secondName = Harvis;
}
2020-05-07 16:06:47.215097+0800 ThirdLibPro[21019:303026] dict : {
    firstName = Song;
    secondName = Harvis;
}
//单独修改可变字典,并不影响不可变字典的值,这是我们想要的,倘若我们把不可变字典的属性关键字声明为strong呢?
2020-05-07 16:06:47.215361+0800 ThirdLibPro[21019:303026] dict : {
    firstName = Song;
    secondName = Harvis;
}
2020-05-07 16:06:47.215557+0800 ThirdLibPro[21019:303026] dict : {
    firstName = Song;
    secondName = Marvis;
}

倘若我们把不可变字典的属性关键字声明为strong:

//一个VC的Interface()中,dict 用strong修饰
@property (nonatomic, strong) NSDictionary *dict;
@property (nonatomic, strong) NSMutableDictionary *dictM;

//做个简单的测验,-viewDidload中
self.dict = @{@"firstName": @"Wong",
                       @"secondName": @"Jarvis"};
self.dictM = [@{@"firstName": @"Song",
                               @"secondName": @"Harvis"} mutableCopy];
self.dict = self.dictM;//这里我们做了赋值,可变字典的值赋给了不可变字典
NSLog(@"dict : %@", self.dict);
NSLog(@"dict : %@", self.dictM);

[self.dictM setObject:@"Marvis" forKey:@"secondName"];//修改可变字典中的一个secondName对应值
NSLog(@"dict : %@", self.dict);
NSLog(@"dict : %@", self.dictM);
//前两个log输出发现可变字典赋值给不可变字典之后,二者的值相同
2020-05-07 16:17:54.048764+0800 ThirdLibPro[21336:309913] dict : {
    firstName = Song;
    secondName = Harvis;
}
2020-05-07 16:17:54.049004+0800 ThirdLibPro[21336:309913] dict : {
    firstName = Song;
    secondName = Harvis;
}
//这里和self.dict声明为copy时就不一致了,我们的代码层面本来的意愿是只修改self.dictM中secondName,可是self.dict中的secondName跟着改变了。这显然违背了程序员的意愿。这中隐性修改self.dict的操作会带来意想不到的错误。
2020-05-07 16:17:54.049563+0800 ThirdLibPro[21336:309913] dict : {
    firstName = Song;
    secondName = Marvis;
}
2020-05-07 16:17:54.049726+0800 ThirdLibPro[21336:309913] dict : {
    firstName = Song;
    secondName = Marvis;
}

所以综上,由于NSDictionry有对应的可变类型,NSMuableDictionry,并且NSMutableDictonry可以赋值给NSDictionry ,代码里有先拿可变字典给不可变字典赋值,然后修改可变字典中的数据,就隐式会改变原来不可变字典中的值。所以针对 NSDictionry的属性操作符,用copy比较适合。

posted @ 2020-05-07 16:25  wjwdive  阅读(473)  评论(0编辑  收藏  举报