I have an iOS app that stores two NSMutableArray‘s as objects in NSUserDefaults in the event that there is no WiFi or Data connectivity. On a subsequent visit, the user should be able to load the stored data in their table by retrieving the saved data from NSUserDefaults, but unfortunately I am unable to do so. The NSMutableArrays are storing objects that hold various NSString values as parameters.
Here is the code that saves my data in my Singleton class:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[DataModel sharedInstance].testResultList forKey:@"resultTable"];
[defaults setObject:[DataModel sharedInstance].testResults forKey:@"jsonTable"];
[defaults synchronize];
and here is the code from UITableView class which is supposed to retrieve the data and load them into a table:
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([[DataModel sharedInstance].testResults count] == 0) {
if ([defaults objectForKey:@"resultTable"] == nil) {
return;
}
else {
[DataModel sharedInstance].testResultList = [defaults objectForKey:@"resultTable"];
[DataModel sharedInstance].testResults = [defaults objectForKey:@"jsonTable"];
}
}
}
and here is my cellForRowAtIndexPath() method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"testresultcell";
ResultTableViewCell *cell = (ResultTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[ResultTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
TestResult *tResult = [[DataModel sharedInstance].testResultList objectAtIndex:indexPath.row];
cell.name.text = tResult.testTitle;
cell.date.text = tResult.dateStamp;
cell.score.text = [[DataModel sharedInstance] getScore:tResult.score];
cell.imgView.image = [UIImage imageNamed:[[DataModel sharedInstance] getImg:tResult.score]];
return cell;
}
Can anyone see what I am doing wrong? I am initially checking to see if the current value of the NSMutableArray‘s are empty. It is only then do I go and check to see if a saved copy of the NSMutableArray exists. If so, then I need to load the array and display the contents in my table.
The typical pattern for doing that is as follows (I usually do it in my ApplicationDelegate):
I don’t see where you registered your default values with NSUserDefaults. If you don’t do that they will not be supplied as default values in the absence of a previously set value.
Then later you can reference the value or set the value using something like:
EDIT: And if it turns out that your DataModel Object (which you didn’t post any code for) cannot be stored because it does not conform to NSCopy rules, then serialize it into an NSData Object which CAN be stored in an NSDictionary, and do it that way.