我正在开发一个包含多组列表的应用。这些将包含许多项目,这些项目将包含更多项目。我想保存并从docs目录中的PList加载它,但我不确定如何在我正在寻找的层次结构中写入数据。这是层次结构:
>Lists
>>List1
>>>Item1
>>>>Item1Details
>>>Item2
>>>>Item2Details
>>>etc.
>>List2
>>>Item1
>>>>Item1Details
>>etc.
我尝试过使用NSDictionary writeToFile,但我仍然不知道如何使用这样的层次结构。
请给我一些关于如何读/写此类事情的指示。我对这种钳子的使用完全不熟悉,所以请耐心等待。
干杯,
HBhargava
答案 0 :(得分:2)
也许,这会对你有帮助。
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
NSString Item1=@"Name";
NSString Item2=@"Age";
NSString Item1Detail=@"Khalid";
NSString Item2Detail=@"21";
NSMutableDictionary *_list1 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *_list2 = [[NSMutableDictionary alloc] init];
[_list1 setValue:Item1Detail forKey:Item1];
[_list1 setValue:Item2Detail forKey:Item2];
[_list2 setValue:Item1Detail forKey:Item1];
[_list2 setValue:Item2Detail forKey:Item2];
NSMutableArray *_lists = [[NSMutableArray alloc] init];
[_lists addObject:_list1];
[_lists addObject:_list2];
[_list1 release]
[_list2 release];
[_lists writeToFile:path atomically:YES];
[_lists release];
答案 1 :(得分:0)
据我所知,你有对象数组,这里是将数组写入doc目录中的plist文件的代码
//look at this code which creates path to plist in documents directory:
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
// >Lists
// >>List1
// >>>Item1
// >>>>Item1Details
// >>>Item2
// >>>>Item2Details
// >>>etc.
// >>List2
// >>>Item1
// >>>>Item1Details
// >>etc.
NSArray *list1Arry = [NSArray arrayWithObjects:@"item1Detail",@"item2Detail",@"item3Detail", nil];
NSArray *list2Arry = [NSArray arrayWithObjects:@"item1Detail",@"item2Detail",@"item3Detail", nil];
NSArray *list3Arry = [NSArray arrayWithObjects:@"item1Detail",@"item2Detail",@"item3Detail", nil];
NSArray *lists = [NSArray arrayWithObjects:list1Arry,list2Arry,list3Arry, nil];
[lists writeToFile: path atomically:YES];
答案 2 :(得分:0)
您可以通过将另一个NSDictionary设置为根目录中的值来构建这样的层次结构。所以,这段代码......
NSMutableDictionary *root = [NSMutableDictionary dictionary];
NSMutableDictionary *child1 = [NSMutableDictionary dictionary];
NSMutableDictionary *child2 = [NSMutableDictionary dictionary];
[child1 setValue:@"leaf1" forKey:@"key1"];
[child1 setValue:@"leaf2" forKey:@"key2"];
[child2 setValue:@"leaf3" forKey:@"key3"];
[child2 setValue:@"leaf4" forKey:@"key4"];
[root setValue:child1 forKey:@"child1"];
[root setValue:child2 forKey:@"child2"];
...会产生这样的根对象:
{
child1: {
key1: leaf1
key2: leaf2
}
child2: {
key3: leaf3
ley4: leaf4
}
}
可以在plist中自动编码的对象类型包括NSString
,NSData
,NSDate
,NSNumber
,NSArray
和{{1} (见API)。