I am developing todo list app for iOS. I have a custom class called ToDoItem. My design is to write the users contents to a text file and read it back from the file when the user again opens the app. I have implemented the methods that confirms to NSCoding protocol for my ToDoItem class.
Method for writing the data is given below
- (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];
}
}
Method for reading the data is given below
- (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];
}
}}
Now I am able to write only single ToDoItem to file and able to read it. If I write more than one object of ToDoItem, while reading it back I get "[NSKeyedUnarchiver initForReadingWithData:]: incomprehensible archive " exception. My concern is I just want to append my ToDoItem objects as and when the user saves the data and retrieve all the information again when the user relaunches the app.
NSCoding methods
- (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;
}
Thanks in advance