我是 ObjectiveC 和 Xcode 的新手,并且会犯错误。这段代码从 getAllRecords 获取一个字典 (myDataPlist)。然后,我在 (myDataPlist) 中制作字典(1 条记录)的可变副本,并用它解密 1 个字段。这非常有效。我只返回该记录(mutCopy)。这也有效。我的问题是原始字典(myDataPlist)发生了变化。它解密的记录也在(myDataPlist)中解密。 2 NSLog(@"%@",myDataPlist) 返回不同的结果。我肯定错过了什么。为什么 (myDataPlist) 发生变化?
感谢您的帮助。
-(NSDictionary *)getRecordForKey:(NSString *)key{
NSDictionary *myDataPlist = [self getAllRecords];
NSMutableDictionary *mutCopy = [[myDataPlist valueForKey:key] mutableCopy];
NSArray *keys = [mutCopy allKeys];
NSData *tData = [[NSData alloc]init];
NSLog(@"%@",myDataPlist);
for (int x = 0; x <= [keys count] - 1; x++) {
if (![keys[x] isEqualToString:@"Template"] && ![keys[x] isEqualToString:@"RecNum"]) {
NSMutableArray *myArray = [mutCopy objectForKey:keys[x]];
tData = myArray[1];
NSString *tString = [tData decryptData:tData withKey:self.settingsManager.masterPad];
myArray[1] = tString;
[mutCopy setObject:myArray forKey:keys[x]];
}
}
NSLog(@"%@",myDataPlist);
return mutCopy ;
}
最佳答案
mutableCopy
仅创建字典的副本,而不创建其内容。因此,您从 [[myDataPlist valueForKey:key] mutableCopy]
收到的字典本质上是一个新字典,其中引用了相同的对象(它不是深拷贝)。
尝试使用
NSMutableDictionary *mutCopy =
[[NSMutableDictionary alloc] initWithDictionary:[myDataPlist valueForKey:key]
copyItems:YES];
而不是mutableCopy
。
摘自苹果文档:
otherDictionary
A dictionary containing the keys and values with which to initialize the new dictionary.
flag
If YES, each object in otherDictionary receives a copyWithZone: message to create a copy of the object—objects must conform to the NSCopying protocol. In a managed memory environment, this is instead of the retain message the object would otherwise receive. The object copy is then added to the returned dictionary. If NO, then in a managed memory environment each object in otherDictionary simply receives a retain message when it is added to the returned dictionary.
如果您的字典包含自定义对象,请确保它们符合 NSCopying 协议(protocol)。
关于iphone - 当副本更改时 NSDictionary 也会更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16159470/