简体   繁体   English

无法保存和加载plist文件

[英]Can't save and load plist file

When i tried to create plist file('Checklist.plist') using following methods i can't see the file in the directory. 当我尝试使用以下方法创建plist文件(“ Checklist.plist”)时,我在目录中看不到该文件。 在此处输入图片说明

- (NSString *)documentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory; }

- (NSString *)dataFilePath {
return [[self documentsDirectory] stringByAppendingPathComponent:@"Checklists.plist"];
}

Why i can't see the file on the directory? 为什么我看不到目录中的文件? How can i solve this problem? 我怎么解决这个问题?

Did you save something in the file? 您是否在文件中保存了一些内容?

NSString *test = @"test";
[test writeToFile:[self dataFilePath] atomically:YES];

If you run this in a simulator, you can NSlog this file path, and than open finder, press cmd + shift + g paste the file path, don't include Checklist.plist , just documents file path, you will see the file you just create named Checklist.plist . 如果您在模拟器中运行此文件,则可以NSlog此文件路径,然后打开finder,按cmd + shift + g粘贴文件路径,不包括Checklist.plist ,仅记录文件路径,您将看到该文件只需创建名为Checklist.plist

This is all my code: 这是我的全部代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSArray *testArray = [NSArray arrayWithObjects:@"test", nil];
    [testArray writeToFile:[self dataFilePath] atomically:YES];
}
- (NSString *)documentsDirectory {
    NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths firstObject];
    return documentsDirectory; 
}

- (NSString *)dataFilePath {
    return [[self documentsDirectory] stringByAppendingPathComponent:@"Checklists.plist"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

The file isn't created when -dataFilePath is called. 调用-dataFilePath时不会创建该文件。

To write a plain string in your file, use: 要在文件中写入纯字符串,请使用:

NSError *e = nil;
[@"blabla" writeToFile:[self dataFilePath] atomically:YES encoding:NSUTF8StringEncoding error:&e];

NSError *e1 = nil;
NSString *fileContents = [NSString stringWithContentsOfFile:[self dataFilePath] encoding:NSUTF8StringEncoding error:&e1];

Both errors should be nil and fileContents should contain the original string. 这两个错误均应为nil,fileContents应包含原始字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM