Matthias Wellkamp
Matthias Wellkamp

Reputation: 128

Save Array to plist

I'm trying to store some items into a pList. Here is the array loop:

for (id obj in items)
NSLog(@"obj: %@", obj);

Output NSLog:

2013-03-27 13:00:40.072 mycode[47436:c07] obj: Red
2013-03-27 13:00:40.073 mycode[47436:c07] obj: Blue
2013-03-27 13:00:40.073 mycode[47436:c07] obj: Green

// The arrayWithObjects works. But I don't know how to (loop?) through my items for saving into the plist file...

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];


    NSFileManager *filemgr;
    filemgr = [NSFileManager defaultManager];

    if ([filemgr fileExistsAtPath: path]) {
        NSLog(@"%@", path);

    NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy];
    NSMutableArray *newArray = [[[NSMutableArray alloc] init] autorelease];
    newArray = [NSArray arrayWithObjects:@"Red", @"Green", @"Blue" nil]; // <--- WORKS!
    newArray = [NSArray arrayWithObjects:items, nil]; // <-- ? 
    [plist setObject:newArray forKey:@"Hi"];
    [plist writeToFile:path atomically:YES];
    [plist release];


    } else {
        NSLog(@"File not found");
    }

    [filemgr release]; 

Upvotes: 4

Views: 5045

Answers (1)

Vishnu
Vishnu

Reputation: 2243

Maybe this piece of code helps you.

NSMutableArray *newArray = [[[NSMutableArray alloc] init] autorelease];
NSMutableArray *targetArray = [[[NSMutableArray alloc] init] autorelease];

newArray = [NSArray arrayWithObjects:@"Red", @"Green", @"Blue" nil];
for(int i=0;i<newArray.count;i++)
{
 [targetArray addObject:[newArray objectAtIndex:i]];

}
[plist setObject:targetArray forKey:@"Hi"];
[plist writeToFile:path atomically:YES];

or another method

NSMutableArray *targetArray = [[[NSMutableArray alloc] init] autorelease];

for (id obj in items)
{
 [targetArray addObject:items];
 }
[plist setObject:targetArray forKey:@"Hi"];
[plist writeToFile:path atomically:YES];

Hope this helps !!!

Upvotes: 1

Related Questions