我正在開發針對iOS的todo列表應用程序。我有一個名爲ToDoItem的自定義類。我的設計是將用戶內容寫入文本文件,並在用戶再次打開應用程序時從文件中讀回。我已經爲我的ToDoItem類實現了確認NSCoding協議的方法。將自定義對象附加到txt文件並將其讀回
用於寫入數據的方法如下
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// if cancel button is pressed
if (sender!=self.saveBtn) {
return;
}
// if save button is pressed
else{
if (self.addField.text.length>0) {
ToDoItem *item = [[ToDoItem alloc] init];
item.itemName = self.addField.text;
item.isDone = FALSE;
item.row = [ToDoListTableTableViewController getCount];
self.toDoItem = item;
NSMutableArray *arr = [NSMutableArray arrayWithContentsOfFile:_appFile];
[arr addObject:item];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arr];
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:_appFile];
[handle seekToEndOfFile];
[handle writeData:data];
[handle closeFile];
}
}
方法給出了讀取數據低於
- (void)loadData{
if ([[NSFileManager defaultManager] fileExistsAtPath:_appFile]) {
NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:_appFile];
if (handle) {
NSData *data = [handle readDataToEndOfFile];
if (data) {
ToDoItem *item;
NSMutableArray *arr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
for (item in arr) {
[_toDoItems addObject:item];
}
}
[handle closeFile];
}
}}
現在我可以只寫單的TodoItem到文件,並能夠讀取它被賦予。如果我寫多個ToDoItem的對象,讀回它時,會得到「[NSKeyedUnarchiver initForReadingWithData:]:難以理解的歸檔」異常。 我的問題是我只想追加我的ToDoItem對象,當用戶保存數據並在用戶重新運行應用程序時再次檢索所有信息。
NSCoding方法
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:_itemName forKey:ITEMNAME];
[aCoder encodeObject:_date forKey:DATE];
[aCoder encodeBool:_isDone forKey:DONE];
[aCoder encodeInteger:_row forKey:ROW];
}
- (id)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self) {
_itemName = [aDecoder decodeObjectForKey:ITEMNAME];
_date = [aDecoder decodeObjectForKey:DATE];
_isDone = [aDecoder decodeBoolForKey:DONE];
_row = [aDecoder decodeIntegerForKey:ROW];
}
return self;
}
在此先感謝
請爲您的'ToDoItem'類顯示您的'NSCoding'方法。順便說一下,在第二個代碼段中,一旦它工作,'arr'將是'ToDoItems'的一個數組,因此您不需要遍歷並將對象添加到數組中 - 您可以簡單地將'arr'分配給'self.toDoItems' – Paulw11
@ Paulw11我已經添加了NSCoding方法。此外,我試着直接設置數組[[toDoItems arrayByAddingObjectsFromArray:arr]。但仍面臨相同的錯誤 – Chandan
@ Paulw11如果文件包含多個項目,則第二個代碼段將引發異常。這就是我得到Stucked的地方 – Chandan