Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading BOOL from plist, writing over it with new value

Tags:

iphone

I've established how to read a BOOL from a plist, but I don't know how to write over the BOOL value I originally read.

The BOOL I'm reading is buried within my plist. When the view loads I take a dictionary from the plist that contains all the info for the view (detail view at the end of a drill down), and the BOOL is inside that dictionary. I can change the value of the BOOL in the dictionary once it's been brought into the app, but I don't know how to write this back to the postion within the plist.

Hopefully this is making sense?

Cheers!

like image 260
Luke Avatar asked Dec 13 '22 14:12

Luke


2 Answers

Write a NSDictionary to a Property List:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"FileName.plist"];

NSDictionary *myDict = [[NSDictionary alloc] init];
[myDict setObject:[NSNumber numberWithBool:YES] forKey:@"myKey"];
[myDict writeToFile:filePath atomically:YES];

Read the Boolean:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"FileName.plist"];

NSDictionary *myDict = [[NSDictionary alloc] initWithContentsOfFile:filePath];
BOOL myBool = [[myDict objectForKey:@"myKey"] boolValue];

You can also put the filePath code into this function:

- (NSString *)getFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"FileName.plist"];
return filePath;
}

And use it like this: (for reading)

NSDictionary *myDict = [[NSDictionary alloc] initWithContentsOfFile:[self getFilePath]];
BOOL myBool = [[myDict objectForKey@"myKey"] boolValue];

And this: (for writing)

NSDictionary *myDict = [[NSDictionary alloc] init];
[myDict setObject:[NSNumber numberWithBool:YES] forKey:@"myKey"];
[myDict writeToFile:[self getFilePath] atomically:YES];
like image 64
Fabio Poloni Avatar answered Jan 04 '23 22:01

Fabio Poloni


For writing BOOL to .plist use below code

NSMutableDictionary* myDict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
[myDict setObject:[NSNumber numberWithBool:YES] forKey:@"LSUIElement"];
[myDict writeToFile:plistPath atomically:NO];

Also have look at the post

like image 42
Jhaliya - Praveen Sharma Avatar answered Jan 04 '23 21:01

Jhaliya - Praveen Sharma