【问题标题】:Save UITableViewController with NSUserDefaults使用 NSUserDefaults 保存 UITableViewController
【发布时间】:2013-05-28 02:29:42
【问题描述】:

我有一个 UITableViewController 类,我想使用 NSUserDefaults 保存它的信息。我的表是通过一个名为“tasks”的数组创建的,它是来自 NSObject 类“New Task”的对象。我如何以及在哪里使用 NSUserDefaults?我知道我必须将我的数组添加为 NSUserDefaults 对象,但我该如何检索它呢?任何帮助,将不胜感激。

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

}

【问题讨论】:

    标签: objective-c


    【解决方案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"];
    

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

    【讨论】:

    • 不需要调用synchronize 来持久化更改,因为它会定期自动调用。只有在您的应用即将退出而您迫不及待时,您才需要调用它。
    【解决方案2】:

    您可以在这里查看以了解如何将对象保存到 NSUserDefaults

    Why NSUserDefaults failed to save NSMutableDictionary in iPhone SDK?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      • 2014-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多