1

通常我将数据保存到 plist (只是我不关心越狱手机是否被黑客入侵的数据,例如用户偏好和其他内容),除非用户首次启动应用程序时,我会像这样创建 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 文件并将其放入包中,并在用户第一次启动应用程序时将其复制到文档目录...

无论如何我可以第一次在objective-c中创建空白plist文件吗应用程序...

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

4

3 回答 3

4
[@{} writeToFile: pathFirstTime atomically: NO];
于 2013-05-01T17:31:11.963 回答
2

创建一个NSArrayorNSDictionary实例并使用writeToFile:atomically:.

于 2013-05-01T17:31:33.910 回答
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);
于 2013-05-01T17:35:53.690 回答