从plist读取BOOL,用新值写下它

时间:2011-04-19 18:22:34

标签: iphone

我已经建立了如何从plist中读取BOOL,但我不知道如何写入我最初阅读的BOOL值。

我正在阅读的BOOL被埋在我的plist中。当视图加载时,我从plist中获取一个字典,其中包含视图的所有信息(向下钻取结束时的详细视图),BOOL在该字典中。一旦它被带入应用程序,我可以在字典中更改BOOL的值,但我不知道如何将其写回到plist中的位置。

希望这有意义吗?

干杯!

3 个答案:

答案 0 :(得分:11)

将NSDictionary写入属性列表:

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];

阅读布尔:

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];

您还可以将filePath代码放入此函数中:

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

并像这样使用:(用于阅读)

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

这:(写作)

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

答案 1 :(得分:2)

将BOOL写入.plist使用以下代码

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

另请查看post

答案 2 :(得分:0)

尝试此功能:

 -(void) setStringToPropertyList:(NSString*) pList withKey:(NSString*)key andValue:(NSString*)val{
//the path.
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [rootPath stringByAppendingPathComponent:pList];
//read the dictionary.
NSMutableDictionary *temp = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
//modify the desired key of the dictionary.
[temp setValue:val forKey:key];
//rewrite the diccionary again.
if([temp writeToFile: plistPath atomically:YES]){
   NSLog(@"setStringToPropertyList: pList updated");
}else{
   NSLog(@"setStringToPropertyList: error writing the file");
}
//memory management
if(!temp) [temp release];
}

此函数允许您将属性写入pList,parameteres:

pList =文件名

key =属性的键

val =属性的值

希望它有所帮助。