我试图阅读很多问题/教程,但我找不到答案!我正在尝试从 textField 中获取字符串并将其保存在我创建的 datas.plist 文件中(在默认键 Root 下)我尝试过以下代码:
//Save Name to plist
if([name.text length] > 0){
NSString *string = name.text;
[array addObject:string];
//plist path
NSString *path = [[NSBundle mainBundle] pathForResource:@"datas" ofType:@"plist"];
//save object
[array writeToFile: path atomically:YES];
}
其中数组是
@interface DetailViewController (){
NSMutableArray* array;
}
但是当我尝试保存时应用程序崩溃(我之前写的操作连接到一个按钮)给出了这个错误:
*由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“无法使用 nil 模型创建 NSPersistentStoreCoordinator”
我认为编写的代码不正确,因为我从不输入要保存的密钥(如@“Root”)或类似的东西。提前致谢
编辑:
我尝试了这段代码,但没有写任何东西:
- (void)addToMyPlist {
NSString *destPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
destPath = [destPath stringByAppendingPathComponent:@"dati"];
// If the file doesn't exist in the Documents Folder, copy it.
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:destPath]) {
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"dati" ofType:@"plist"];
[fileManager copyItemAtPath:sourcePath toPath:destPath error:nil];
}
// Load the Property List.
array = [[NSMutableArray alloc] initWithContentsOfFile:destPath];
//NSString *path = [[NSBundle mainBundle] pathForResource:@"dati" ofType:@"plist"];
NSString *string = self.name.text;
NSArray *values = [[NSArray alloc] initWithObjects:string, nil];
NSArray *keys = [[NSArray alloc] initWithObjects:@"Root", nil];
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:values forKeys:keys];
[array addObject:dict];
[array writeToFile:destPath atomically:YES];
}
怎么了?