技术开发 频道

新手必读:iPhone SDK示例代码解析

  Plist文件

  应用程序特定的plist文件可以被保存到app bundle的Resources文件夹。当应用程序运行起来的时候,就会去检查是不是有一个plist文件在用户的Documents文件夹下。假如没有的话,就会从app bundle目录下拷贝过来。

// Look in Documents for an existing plist file
NSArray
*paths = NSSearchPathForDirectoriesInDomains(
    NSDocumentDirectory, NSUserDomainMask, YES);
NSString
*documentsDirectory = [paths objectAtIndex:0];
myPlistPath
= [documentsDirectory stringByAppendingPathComponent:
    [NSString stringWithFormat: @
"%@.plist", plistName] ];
[myPlistPath retain];

// If it's not there, copy it from the bundle
NSFileManager *fileManger = [NSFileManager defaultManager];
if ( ![fileManger fileExistsAtPath:myPlistPath] ) {
    NSString
*pathToSettingsInBundle = [[NSBundle mainBundle]
        pathForResource:plistName ofType:@
"plist"];
}        

 

  现在我们就可以从Documents文件夹去读plist文件了。

NSArray *paths = NSSearchPathForDirectoriesInDomains(
    NSDocumentDirectory, NSUserDomainMask, YES);
NSString
*documentsDirectoryPath = [paths objectAtIndex:0];
NSString
*path = [documentsDirectoryPath
    stringByAppendingPathComponent:@
"myApp.plist"];
NSMutableDictionary
*plist = [NSDictionary dictionaryWithContentsOfFile: path];

 

  Now read and set key/values

myKey = (int)[[plist valueForKey:@"myKey"] intValue];
myKey2
= (bool)[[plist valueForKey:@"myKey2"] boolValue];

[plist setValue:myKey forKey:@
"myKey"];
[plist writeToFile:path atomically:YES];
0
相关文章