Search code examples
ios5nsmutablearrayplistarchive

Save a mutable array with multiple properties to a plist


I have a mutable array that has about 100 objects in it and each object has three properties. I cannot save this to a plist?? I can save an array that just has objects without properites, but the individual property thing is giving me a problem. Any suggestions? Also, is saving to a plist the best way to do this? thanks in advance.


Solution

  • You can store NSDictionary inside NSDictionary, or maybe you mean a NSArray that holds NSDictionary?

    NSMutableArray *myArray = [[NSMutableArray alloc] init];
    
    NSMutableDictionary *myDict1 = [[NSMutableDictionary alloc] init];
    [myDict1 setValue:@"string 1" forKey:@"item_1"];
    [myDict1 setValue:@"string 2" forKey:@"item_2"];
    [myDict1 setValue:[NSNumber numberWithInt:10]   forKey:@"item_3"];     
    
    // add the array 3 times
    [myArray addObject:myDict1];
    [myArray addObject:myDict1];
    [myArray addObject:myDict1];
    NSLog(@"%@", myArray);
    
    // write to plist    
    [myArray writeToFile:@"/tmp/array_with_dict.plist" atomically:YES];
    
    // dict inside dict
    NSMutableDictionary *mainDict = [[NSMutableDictionary alloc] init];
    [mainDict setValue:myDict1 forKey:@"dict_1"];
    
    // write to plist
    [mainDict writeToFile:@"/tmp/dict_with_dict.plist" atomically:YES];