Search code examples
iphoneobjective-cios4plistwritetofile

Writing Data to Plist as a Hierarchy


I am working on an app that contains several sets of lists. These will contain a lot of items which will in turn contain more items. I want to save and load this to/from a PList in the docs directory, but I am unsure of how to write data in the hierarchy that I am looking for. This is the hierarchy:

>Lists
>>List1
>>>Item1
>>>>Item1Details
>>>Item2
>>>>Item2Details
>>>etc.
>>List2
>>>Item1
>>>>Item1Details
>>etc.

I have tried using NSDictionary writeToFile, but I still do not know how to have such a hierarchy.

Please give me some pointers on how to read/write this kind of thing. I am completely new to this use of plists, so please bear with me.

Cheers,

HBhargava


Solution

  • Perhaps, this will help you.

    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];