objective-cioscordovaplistdocumentsdirectory

Error writing to plist in documents directory


I use the following code to copy a Resources plist file into the documents directory:

BOOL success;
NSError *error;

NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Test-Info.plist"];

success = [fileManager fileExistsAtPath:filePath];

if (!success) {
    NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:@"Test-Info.plist"];
    success = [fileManager copyItemAtPath:path toPath:filePath error:&error];
    NSLog(@"Test-Info.plist successfully copied to DocumentsDirectory.");
}

I get the success message, which is great. I'm assuming it's been copied correctly into the documents folder.

However when I then try to read and write to the saved plist file it returns null:

Key entry in Test-Info.plist:

Key: EnableEverything
Type: Boolean
Value: YES

Write code:

NSString *adKey = @"EnableEverything";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@"Test-Info.plist"];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];

NSString *enableEverything = [[plist valueForKey:adKey] stringValue];
NSLog(@"****** EXISTING: %@ ******", enableEverything); // returns (null)

// Disable in plist.
[plist setValue:0 forKey:adKey]; // will this work?
[plist writeToFile:path atomically:YES]; // this doesn't throw an error?

NSString *enableEverything1 = [[plist valueForKey:adKey] stringValue];
NSLog(@"****** NOW: %@ ******", enableEverything1); // returns (null)

Output:

****** EXISTING: (null) ******
****** NOW: (null) ******

My question is why are they (null) when they exist within the plist file?


Solution

  • You are trying to mutate an immutable object.

    You need a NSMutableDictionary.

    IE

    NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile: path] mutableCopy];
    

    Also check, if the plist object isnt nil, as any messages can be send to nil without raiing an error. this wouldnt fail, also nothing actually happens.

    [plist setValue:0 forKey:adKey]; // will this work?
    [plist writeToFile:path atomically:YES]; // this doesn't throw an error?
    

    as the source path is nil, you are most like not copying the file during compilation bundling. drag it here:

    enter image description here