objective-c - b/w addObject :dictionary and addObject:[dictionary copy] to an NSMutableArray? 有什么区别

标签 objective-c ios xcode4 nsmutablearray nsmutabledictionary

我正在尝试在循环中为我的 NSMutableDictionary 设置一些值,并将字典值每次分配给 NSMutableArray,如下所示,

for(int i=0;i<=lastObj;i++){
[mutableDict setValue:[valuesArray objectAtIndex:i] forKey:@"Name"];
[mutableDict setValue:[uniqueArray objectAtIndex:i] forKey:@"SSN"];
//......then
**[mutableArray addObject:mutableDict];**/*not working perfectly all values s replaced by final mutableDict values (duplicate values)*/

但是

**[mutableArray addObject:[mutableDict copy]];**/* Working Correctly !!! */
}

在每次迭代中的内部循环中,新值被分配给 mutableDictionary,每当我说 addObject 时,我的 mutableArray 会获取所有重复值,但每当我说 addObject:[mutableDict copy] 时,数组就会变得正确且唯一没有任何重复的值,我不知道当我说复制时编译器有什么区别,谁能告诉我这方面的区别。 提前致谢。

最佳答案

[mutableArray addObject:mutableDict];

继续将 mutableDict 添加到 mutableArray。添加对象不会创建新的内存位置,它指向相同的内存。所以当你设置 mutableDict 的值时,它会反射(reflect)在所有添加的对象中,因为它们引用相同的内存位置。

复制创建一个新的内存位置并添加对象以消除上述情况。

为了避免这种情况你可以添加

for(int i=0;i<=lastObj;i++){
NSMutableDictionary * mutableDict = [NSMutableDictionary new]; //create new memory location
[mutableDict setValue:[valuesArray objectAtIndex:i] forKey:@"Name"];
[mutableDict setValue:[uniqueArray objectAtIndex:i] forKey:@"SSN"];

[mutableArray addObject:mutableDict];
[mutableDict release]; //release 
}

希望对你有帮助。快乐的编码:)

关于objective-c - b/w addObject :dictionary and addObject:[dictionary copy] to an NSMutableArray? 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10532212/

相关文章:

Objective-C 运行时 : What does declaring a variable of type Class (objc_class) conforming to a protocol mean?

ios - 无法在 XCode iOS 中将系统路径设置为 header 搜索路径

ios - 通过 firebase 的音频流

iphone - Objective-C 中的协议(protocol)范例

ios - 在 iOS 中分发小部件的最佳方式

unit-testing - 将在设备上运行的单元测试添加到现有的 Xcode 4 项目

ios - 设置动态 UITableViewCell 高度

ios - 当我们在 ios 中的长按手势上有 tableview 单元格的索引路径时,如何在单元格中获取按钮的引用作为 subview

iOS 开发 : Certificates and hiring a freelancer

ios - 延迟类选择器调用