Question

I have an array of Objects (containing an item name and a creation date) used to display table data. I want to save this array using NSCoding protocol. I call my saveDataToDisk method every time a "submit" button is pressed to submit a new table entry. However, my app crashes upon hitting submit. This is my first time learning how to save app data and I looked a several tutorials and my form seems to be the same. I also looked for several days on the internet and couldn't find a solution. What is wrong?

Here are my methods:

Decoder Method:

- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
    return nil;
}
self.itemArray = [decoder decodeObjectForKey:@"itemArray"];
return self;
}

Encoder Method:

- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.itemArray forKey:@"itemArray"];
}

Path Finder Method:

- (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];
}

Save Data Method:

- (void) saveDataToDisk
{
NSString * path = [self pathForDataFile];

NSMutableDictionary * rootObject;
rootObject = [NSMutableDictionary dictionary];

[rootObject setValue: [self itemArray] forKey:@"itemArray"];
[NSKeyedArchiver archiveRootObject: rootObject toFile: path];
}

Load Data Method:

- (void) loadDataFromDisk
{
NSString     * path        = [self pathForDataFile];
NSDictionary * rootObject;

rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
[self setItemArray: [rootObject valueForKey:@"itemArray"]];
}

My Button:

- (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];
}

}
Was it helpful?

Solution

You are trying to save an NSArray with custom objects.

Your objects must implement NSCoding protocol as well.

Implement those:

- (id)initWithCoder:(NSCoder *)decoder
- (void)encodeWithCoder:(NSCoder *)encoder

in your "Data" class. NSArray is going through all objects and call those methods for each object inisde an array

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top