Search code examples
iphoneobjective-cipadplistread-write

Plist Read and Write iPhone


I am having troubles with my class which reads and writes data to a plist. Here is some code:

This first chunk is from my custom class with all my plist read and write methods.

-(NSString *) dataFilePath{
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [path objectAtIndex:0];
    return [documentDirectory stringByAppendingPathComponent:@"userInformation.plist"];
}

-(bool)readUserIsMale{
    NSString *filePath = [self dataFilePath]; 
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {        
        NSDictionary *boolDict = [[NSDictionary alloc] initWithContentsOfFile:[self dataFilePath]];
        return [[boolDict objectForKey:@"boolUserIsMale"] boolValue];
    }
    return nil;
}

-(void)writeUserIsMale:(bool)boolValue{
    NSDictionary *boolDict = [[NSDictionary alloc] init];
    [boolDict setValue:[NSNumber numberWithBool:boolValue] forKey:@"boolUserIsMale"];
    [boolDict writeToFile:[self dataFilePath] atomically:YES];
}

I then in another class where desired import, create and use the class methods:

#import "plistReadWrite.h"
plistReadWrite *readWrite;

If I try and see its value in the console I get (null) return.

NSLog(@"%@",[readWrite readUserIsMale]);

This is of course after I have written some data like so:

[readWrite writeUserIsMale:isUserMale];

isUserMale being a bool value.

Any help would be massively appreciated, if you need anymore info let me know. Thanks.


Solution

  • I think this is mostly correct. In your writeUserIsMale: method you want a mutable dictionary, so you can actually set that key (this should have crashed for you as is, so I'm guessing a copy/paste problem?)

    //NSDictionary *boolDict = [[NSDictionary alloc] init];
    //should be:
    
    NSMutableDictionary *boolDict = [[NSMutableDictionary alloc] init];
    

    And then when you log the value, remember that bool (or BOOL) are primitives, not objects so:

    NSLog (@"%d",[readWrite readUserIsMale]); // Will print 0 or 1
    // or if you prefer:
    NSLog (@"%@", ([readWrite readUserIsMale]? @"YES":@"NO")); // print YES or NO
    

    Lastly, since this is objective-c, I would probably use BOOL instead of bool.

    I'm assuming this is just a simple example, and that you know about NSUserDefaults for this sort of thing.

    Hope that helps.