0
我有一個用於顯示錶格數據的對象數組(包含項目名稱和創建日期)。我想用NSCoding協議保存這個數組。每次按下「提交」按鈕提交新表格條目時,我都會調用saveDataToDisk方法。但是,我的應用程序在提交時崩潰。這是我第一次學習如何保存應用程序數據,我看了幾個教程,我的表單看起來是一樣的。我也在網上找了幾天,找不到解決辦法。哪裏不對?無法通過NSCoding保存表格數據
這裏是我的方法:
譯碼方法:
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
self.itemArray = [decoder decodeObjectForKey:@"itemArray"];
return self;
}
編碼方法:
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.itemArray forKey:@"itemArray"];
}
路徑查找器方法:
- (NSString*) pathForDataFile
{
NSFileManager * fileManager = [NSFileManager defaultManager];
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"appData"];
if([fileManager fileExistsAtPath:filePath] == NO)
{
[fileManager createDirectoryAtPath:filePath withIntermediateDirectories:NO attributes:nil error:nil];
}
NSString *fileName = @"Budgetlist.appData";
return [filePath stringByAppendingPathComponent: fileName];
}
保存數據的方法:
- (void) saveDataToDisk
{
NSString * path = [self pathForDataFile];
NSMutableDictionary * rootObject;
rootObject = [NSMutableDictionary dictionary];
[rootObject setValue: [self itemArray] forKey:@"itemArray"];
[NSKeyedArchiver archiveRootObject: rootObject toFile: path];
}
加載數據的方法:
- (void) loadDataFromDisk
{
NSString * path = [self pathForDataFile];
NSDictionary * rootObject;
rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
[self setItemArray: [rootObject valueForKey:@"itemArray"]];
}
我的按鈕:
- (IBAction)submitButton:(id)sender {
if (self.textField.text.length > 0 && [self.textField.text floatValue]>0) {
self.item = [[Data alloc] init];
self.item.itemName = self.textField.text;
[self.itemArray addObject:self.item];
[self.tableView reloadData];
[self saveDataToDisk];
}
}
謝謝你做到了。 – somethingstrang