Search code examples
iphoneiosplistnsdate

save NSDate value to plist


I am trying to figure out how to save a NSDate value into my plist file thats in my application.

I am currently doing this but am stuck on the actual part where I have to save it.

NSString *datePlistPath = [[NSBundle mainBundle] pathForResource: @"my-Date" ofType: @"plist"];
        NSMutableDictionary *dict = [NSDictionary dictionaryWithContentsOfFile: datePlistPath];

        // to be saved to plist
        NSDate *date = [NSDate date];

// this is where I start to get abit lost, I want to set the date to the right plist value then commit the changes
        [dict setObject:date forKey:@"my-Date"];
        [dict writeToFile:datePlistPath atomically:YES]; // error happening here.

any help would be appreciated

UPDATE: once it hits the last line of code there this is the error that is generated...

* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'


Solution

  • Use NSMutableDictionary dictionaryWithContentsOfFile

    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile: datePlistPath];
    

    it provide u NSDictionary not NSMutableDictionary if u use NSDictionary dictionaryWithContentsOfFile

    Also u cannot update plist in application bundle instead store in Document Directory.

    Refer dit-objects-in-array-from-plist link