writing NSDictionary to plist in my app bundle
Asked Answered
F

2

9

I'm trying to write an NSDictionary to a plist but when I open the plist no data has been written to it. From the log my path looks correct and my code is pretty standard. Any ideas?

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", @"key3", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", @"value3", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

NSString *path = [[NSBundle mainBundle] pathForResource:@"FormData" ofType:@"plist"];
NSLog(@"path:%@", path);

[dictionary writeToFile:path atomically:YES];
Filide answered 23/3, 2010 at 17:34 Comment(0)
D
24

Johan is right -- you're not allowed to modify your app's bundle. You have two good options for where to save your dictionary: the documents directory, which is backed up by iTunes when a user syncs their device; or the caches directory, which is not backed up. If you don't need to have the data backed up, put it in caches so you don't slow down syncing. You can get the directory paths like so:

NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *cachesDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
Diplomatics answered 23/3, 2010 at 18:41 Comment(1)
I think this probably needs an additional info now that document sharing exists. From Apple: "If you do not want files to be shared with the user, put them in your application’s Library directory. If none of the standard Library subdirectories are appropriate, create a private directory inside the Library directory and give it the name of your application’s bundle ID. You can then use that directory to store any files that are private to your application."Dateline
P
5

It doesn't get saved because you can't write into your app's bundle. Save your file elsewhere, in the documents folder for example.

Poussette answered 23/3, 2010 at 17:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.