0

I have a UITableViewController class and I want to save its information using NSUserDefaults. My table is created through an array called "tasks" which are objects from an NSObject class "New Task". How and where do I use NSUserDefaults? I know that I have to add my array as a NSUserDefaults object, but how do I go about retrieving it? Any help would be appreciated.

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *DoneCellIdentifier = @"DoneTaskCell";
    static NSString *NotDoneCellIdentifier = @"NotDoneTaskCell";
    NewTask* currentTask = [self.tasks objectAtIndex:indexPath.row];
    NSString *cellIdentifer = currentTask.done ? DoneCellIdentifier : NotDoneCellIdentifier;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer forIndexPath:indexPath];

    if(cell==nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifer];

    }

    cell.textLabel.text = currentTask.name;
    return cell;
}

This is my viewdidload method:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.tasks = [[NSMutableArray alloc]init];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.tasks forKey:@"TasksArray"];

}

user2200321
  • 325
  • 1
  • 4
  • 18

2 Answers2

1

Write data to user defaults doing:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; 
[userDefaults setObject:self.tasks forKey:@"TasksArray"];

// To be sure to persist changes you can call the synchronize method
[userDefaults synchronize];

Retrieve data from user defaults doing:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; 
id tasks = [userDefaults objectForKey:@"TasksArray"];

However, you can only store objects of type NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary (array and dictionaries can only contain objects of that list). If you need to store some other object, you can use a NSKeyedArchiver to convert your object into NSData and then store it, and a NSKeyedUnarchiver to awake your object form the data.

vilanovi
  • 2,097
  • 2
  • 21
  • 25
  • 1
    It is not required to call `synchronize` to persist changes, as it is automatically invoked at periodic intervals. You only would need to call it if your app was about to exit and you could not wait. – terry lewis May 28 '13 at 03:11
0

You can see here to know how to save an object to NSUserDefaults

Why NSUserDefaults failed to save NSMutableDictionary in iPhone SDK?

Community
  • 1
  • 1
Tony
  • 4,311
  • 26
  • 49