以编程方式创建空白plist(在DocumentsDirectory中)

时间:2013-05-01 17:28:14

标签: ios objective-c plist bundle createfile

通常情况下,我将数据保存到plist(只是我不太关心的数据,如果JailBroken手机被黑客攻击,比如用户偏好和内容),除非用户首次启动应用程序时我创建了这样的plist:

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *pathFirstTime = [documentsDirectory stringByAppendingPathComponent:@"FirstTime.plist"];

NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: pathFirstTime])
{
    NSString *bundleFirstTime = [[NSBundle mainBundle] pathForResource:@"FirstTime" ofType:@"plist"];

    [fileManager copyItemAtPath:bundleFirstTime toPath:pathFirstTime error:&error];
}

所以我在xcode中创建一个空白plist文件并将其放入包中,第一次用户启动应用程序时将其复制到documentsDirectory ...

无论如何,我可以在objective-c中第一次创建空白plist文件,这样我实际上不必在Xcode中创建一个并将其放入包中,但它会在第一次自动创建用户启动应用程序......

基本上只是避免使用此代码:[fileManager copyItemAtPath:bundleFirstTime toPath:pathFirstTime error:&error];

3 个答案:

答案 0 :(得分:4)

[@{} writeToFile: pathFirstTime atomically: NO];

答案 1 :(得分:2)

创建NSArrayNSDictionary个实例并使用writeToFile:atomically:

答案 2 :(得分:0)

删除整个代码,这样做就可以了。

    if(![[NSUserDefaults standardUserDefaults] objectForKey:@"FirstRun"]){
            NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *pathFirstTime = [documentsDirectory stringByAppendingPathComponent:@"MyPlistFile.plist"];

            [@{} writeToFile: pathFirstTime atomically: YES];

            [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:NO] forKey:@"FirstRun"];
        }

想要添加新记录吗?

        NSString *pathFirstTime = [documentsDirectory stringByAppendingPathComponent:@"MyPlistFile.plist"];
        NSMutableDictionary *mdic = [[NSMutableDictionary alloc] initWithDictionary:[NSDictionary dictionaryWithContentsOfFile:pathFirstTime]];

        [mdic setObject:[NSNumber numberWithInt:3] forKey:@"user-selected-color-scheme"];
        [mdic writeToFile: pathFirstTime atomically: YES];

稍后阅读plist文件?

        NSString *pathFirstTime = [documentsDirectory stringByAppendingPathComponent:@"MyPlistFile.plist"];
        NSMutableDictionary *mdic = [[NSMutableDictionary alloc] initWithDictionary:[NSDictionary dictionaryWithContentsOfFile:pathFirstTime]];
        NSLog(@"%@", mdic);