2013-05-28 162 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'堅持的變化,因爲它是在週期性間隔自動調用。如果您的應用即將退出,並且您無法等待,您只需要調用它。 –