Sahitya Tarumani
Sahitya Tarumani

Reputation: 429

overwriting instead of writing to a plist-cocoa

I have created a method to write data to a plist.

- (void)writeToPListUserType:(NSString *)type 
                   andUserID:(NSString *)usid 
                andFirstName:(NSString *)fname 
                 andLastName:(NSString *)lname 
                 andPassword:(NSString *)pwd{

    NSMutableDictionary *userDetails = [[NSMutableDictionary alloc] init];
    [userDetails setObject:fname forKey:@"firstName"];
    [userDetails setObject:lname forKey:@"lastName"];
    [userDetails setObject:pwd forKey:@"password"];

    NSMutableDictionary *userIDKey = [[NSMutableDictionary alloc] init];
    [userIDKey setObject:userDetails forKey:usid];

    [userCredentials setObject:userIDKey forKey:type];
    [userIDKey release];
    [userDetails release];

    NSString *error;

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

    NSString *plistPath = [rootPath stringByAppendingPathComponent:
                                                     @"userCredentials.plist"];

    NSData *plistData = [NSPropertyListSerialization
                                           dataFromPropertyList:userCredentials
                                            format:NSPropertyListXMLFormat_v1_0
                                                      errorDescription:&error];

    [plistData writeToFile:plistPath atomically:YES];
}

I am able to write new data to the plist. However, when the new data is written, the old data is no longer there. In other words, the method is overwriting my plist.
Please tell me what is wrong with the method... :(

Thanks in advance...

Upvotes: 0

Views: 568

Answers (2)

viggio24
viggio24

Reputation: 12366

With this line:

code>[userCredentials setObject:userIDKey forKey:type];

you are overwriting the existing "userCredentials" "type" key (I don't see it is newly allocated in the method) with new data.

So the userCredentials, which I suppose is a mutable dictionary created elsewhere, is overwritten with the new data.

Upvotes: 1

justin
justin

Reputation: 104708

1) read the plist from disk

2) create a mutable in memory copy

3) modify the (in memory) plist

4) overwrite the file you read, using the in memory plist

Upvotes: 1

Related Questions