我有NSMutableArray
NSMutableDictionary
但是当我访问数组的值时,它们总是为零。这是我正在使用的代码
NSMutableDictionary *tmpDictionary = [[NSMutableDictionary alloc] init];
self.arrayOfData = [[NSMutableArray alloc] init];
[tmpDictionary setObject:@aaa forKey:Key1];
[tmpDictionary setObject:@1 forKey:Key2];
[tmpDictionary setObject:@1 forKey:Key3];
[tmpDictionary setObject:@10.0f forKey:Key4];
[tmpDictionary setObject:@10.0f forKey:Key5];
[self.arrayOfData addObject:tmpDictionary];
[tmpDictionary removeAllObjects];
[tmpDictionary setObject:@bbb forKey:Key1];
[tmpDictionary setObject:@1 forKey:Key2];
[tmpDictionary setObject:@2 forKey:Key3];
[tmpDictionary setObject:@50.0f forKey:Key4];
[tmpDictionary setObject:@50.0f forKey:Key5];
[self.arrayOfData addObject:tmpDictionary];
[tmpDictionary removeAllObjects];
我以这种方式访问数组
for (int i = 0; i < self.arrayOfData.count; ++i) {
NSLog(@"%@", [self.arrayOfData[i] objectForKey:Key3]);
}
但是日志总是返回nil。 我的错是什么? 提前致谢
答案 0 :(得分:3)
只有一个字典,它是可变的。调用[tmpDictionary removeAllObjects];
时,将删除所有对象,因此之后为空。要解决此问题,请创建多个可变字典,并且不要清空它们。
答案 1 :(得分:3)
问题是由于重复使用tmpArray
并从阵列中删除所有对象。那不行。这样做:
self.arrayOfData = [[NSMutableArray alloc] init];
NSMutableDictionary *tmpDictionary = [[NSMutableDictionary alloc] init];
[tmpDictionary setObject:@aaa forKey:Key1];
[tmpDictionary setObject:@1 forKey:Key2];
[tmpDictionary setObject:@1 forKey:Key3];
[tmpDictionary setObject:@10.0f forKey:Key4];
[tmpDictionary setObject:@10.0f forKey:Key5];
[self.arrayOfData addObject:tmpDictionary];
tmpDictionary = [[NSMutableDictionary alloc] init];
[tmpDictionary setObject:@bbb forKey:Key1];
[tmpDictionary setObject:@1 forKey:Key2];
[tmpDictionary setObject:@2 forKey:Key3];
[tmpDictionary setObject:@50.0f forKey:Key4];
[tmpDictionary setObject:@50.0f forKey:Key5];
[self.arrayOfData addObject:tmpDictionary];
更好的是使用现代语法:
self.arrayOfData = [[NSMutableArray alloc] init];
NSDictionary *tmpDictionary = @{
Key1 : @aaa",
Key2 : @1,
Key3 : @1,
Key4 : @10.0f,
Key5 : @10.0f
};
[self.arrayOfData addObject:tmpDictionary];
tmpDictionary = @{
Key1 : @bbb",
Key2 : @1,
Key3 : @2,
Key4 : @50.0f,
Key5 : @50.0f
};
[self.arrayOfData addObject:tmpDictionary];
答案 2 :(得分:2)
@rmaddy是对的。
同样小的补充。
您可能认为-addObject:
方法将字典对象复制到数组(创建对象的副本)。它没有
。
它只存储字典中tmpDictionary
的引用。你基本上保存指向具有你的字典的内存部分的指针。
您在代码中执行的操作:
从字典中删除oll对象(此时数组中的对象将为空)
创建NSMutableDictionary的另一个实例
为了说明这一点 - 在第一次将字典添加到数组之后放置此NSLog
。此NSLog将打印tmpDictionary和数组项的内存地址,索引为0.您将看到它是完全相同的对象
NSLog(@"tmpDictionary: %p, Array Item 0: %p", tmpDictionary, self.arrayOfData[0]);
希望我解释得很好......