创建一个NSMutableArray,其中包含几个NSMutableDictionary对象
我环顾四周,看到有关排序NSMutableArray的包含NSDictionaries,但一直没有找到一些具体的例子,如何实际上使NSMutableArray组成NSDictionaries的一些具体的例子。创建一个NSMutableArray,其中包含几个NSMutableDictionary对象
我正在使用NSUserDefaults跟踪用户对几个不同项目的偏好。 NSMutableArray将用于跟踪总项目,而NSDictionaries则用于每个项目的个人偏好。
我已经写了这些方法来跟踪我的偏好类中的项目,但我不太清楚如何初始化NMutableArray以包含NSDictionaries。
-(NSMutableArray *)deviceListArray
{
return [[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:@"device_list_array"];
}
-(void) setDeviceListArray:(NSMutableArray *)deviceListArray
{
[[NSUserDefaults standardUserDefaults] setObject:deviceListArray forKey:@"device_list_array"];
}
如果任何人都可以指出我正确的方向,我会非常感激。非常感谢你!或者如果某人有更好的策略来跟踪物品,每种物品都有不同的喜好,那么这也会很棒!
谢谢!
一旦你将一个对象传递给userDefaults,它拥有该对象 - 所以你不能去改变它里面的字典的属性。
你可以做的是一个双向复制,其中你有一个可变字典的局部可变数组。您将创建一个新的可变数组,然后为每个可变字典调用[NSDictionary dictionaryWithDictionary:],将新的不可变字典添加到新数组中。
如果您在字典中埋藏了可变对象,那么您需要为此做同样的事情。所有这一切说,如果你有这么多的东西,我怀疑你没有正确地考虑如何使用默认系统。我几乎总是只保存字符串,数字,颜色等
编辑:代码
NSMutableArray *array = [NSMutableArray arrayWithCapacity:10];
for(int i=0; i<10; ++i) {
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:10];
// add stuff to the dictionary
[array addObject:dict];
}
// later on want to change second dictionary:
NSMutableDictionary *dict = [array objectAtIndex:1];
// fool around with dict
// no need to re-save it in array, since its mutable
不知道这是否是你想要的功能:
#define kDeviceKey1 @"DeviceKey1"
#define kDeviceKey2 @"DeviceKey2"
#define kDeviceKey3 @"DeviceKey3"
#define kDeviceKey4 @"DeviceKey4"
#define kDeviceID @"DeviceID"
NSMutableArray *devices = [[NSMutableArray alloc]init];
NSMutableDictionary *deviceInfo = [[NSMutableDictionary alloc]init];
// create a dictionary record for earch device which contains thing...
// probably employ some kind of loop
deviceInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:1], kDeviceID,
// @"DeviceName1", kDeviceID, // or this
@"whateverthing1forDevice1", kDeviceKey1,
@"whateverthing2forDevice1", kDeviceKey2,
@"whateverthing3forDevice1", kDeviceKey3,
@"whateverthing4forDevice1", kDeviceKey4,
nil];
[devices addObject:deviceInfo];
// this is just an example, you would have some kind of loop to replace "whateverthing1forDevice1" with actual data
deviceInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:2], kDeviceID,
// @"DeviceName2", kDeviceID, // or this
@"whateverthing1forDevice2", kDeviceKey1,
@"whateverthing2forDevice2", kDeviceKey2,
@"whateverthing3forDevice2", kDeviceKey3,
@"whateverthing4forDevice2", kDeviceKey4,
nil];
[devices addObject:deviceInfo];
NSLog(@"devices: %@", devices);
嘿谢谢一堆例子。你是否也可以给我一些在设备内部抓取“whateverthing2forDevice2”的语法。我是否必须抓住字典,然后从那里抓取它,还是可以一次完成? – 2012-08-01 00:44:21
我现在将它作为一个两步,所以这不是什么大问题。我只是想知道这是否可能 – 2012-08-01 01:11:04
嘿感谢大卫。我其实没有那么多偏好。它与显示无关,仅与外部设备进行交互,而且我只需要为每个设备保存大约4件事情。你能否详细说明在其中分配可变字典的可变数组的正确方法?这是真的把我扔了。我只是无法找到一个好例子。 – 2012-07-31 01:43:27
我添加了一个例子。 – 2012-07-31 11:14:01