2013-05-28 116 views
0

我有一个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"]; 

}

回答

1

写入数据到用户默认设置做:

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

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

检索用户的默认数据做:

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

但是,可以只NSData类型,NSStringNSNumberNSDateNSArray,或者NSDictionary的存储对象(阵列和字典只能包含该列表的对象)。如果您需要存储其他对象,则可以使用NSKeyedArchiver将对象转换为NSData然后存储它,并使用NSKeyedUnarchiver将对象从数据中唤醒。

+1

它不需要调用'synchronize'坚持的变化,因为它是在周期性间隔自动调用。如果您的应用即将退出,并且您无法等待,您只需要调用它。 –