我有一個UITableViewController類,我想用NSUserDefaults保存它的信息。我的表是通過一個名爲「tasks」的數組創建的,它是NSObject類「New Task」中的對象。我如何以及在哪裏使用NSUserDefaults?我知道我必須將我的數組添加爲NSUserDefaults對象,但我該如何去檢索它?任何幫助,將不勝感激。用NSUserDefaults保存UITableViewController
- (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;
}
這是我的viewDidLoad方法:
- (void)viewDidLoad
{
[super viewDidLoad];
self.tasks = [[NSMutableArray alloc]init];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:self.tasks forKey:@"TasksArray"];
}
它不需要調用'synchronize'堅持的變化,因爲它是在週期性間隔自動調用。如果您的應用即將退出,並且您無法等待,您只需要調用它。 –