ios - 保存 NSUserDefault 数据并在 TableView 中显示

标签 ios uitableview nsarray nsuserdefaults

我正在尝试通过 NSUserDefaults 保存我的数据并在 TableView 中查看它。我已经将四个文本数据设置为一个数组(dataArray),以便我可以在 TableView 中查看它。但我无法将数据加载到 TableView 中。那么我错过了什么吗?

提前致谢。

-(IBAction)save{

NSUserDefaults *add1 = [NSUserDefaults standardUserDefaults];
[add1 setObject:txt1 forKey:@"txt1"];
[add1 setObject:txt2 forKey:@"txt2"];
[add1 setObject:txt3 forKey:@"txt3"];
[add1 setObject:txt4 forKey:@"txt4"];

[add1 synchronize]; 
}

- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
self.dataArray = [NSArray arrayWithObjects:[prefs objectForKey:@"txt1"], [prefs objectForKey:@"txt2"], [prefs objectForKey:@"txt3"],[prefs objectForKey:@"txt4"] nil];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

// Set up the number of rows
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *string = [dataArray objectAtIndex:indexPath.row];
    static NSString *CellIdentifier = @"Cell";

    UITableView *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
}

最佳答案

你必须调用[yourUserDefaultObject Synchronize];来保存NSUserDefaults的状态,但你实际上并不需要创建4个NSUserDefaults对象,你可以只需创建一次,然后在同一个实例上调用 setObject:forKey:,然后synchronize
然后只需在 cellForRowAtIndexPath 回调中设置 cell.textLabel.text=string; 即可设置单元格的标签。

关于ios - 保存 NSUserDefault 数据并在 TableView 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10460655/

相关文章:

java - 如何使用appium消除android的警报弹出窗口

ios - swift 将表格 View 的大小调整到最后一行

UITableView reloadRowsAtIndexPaths 在不应该的时候执行动画

arrays - 快速 array.removeAtIndex 错误

ios - NSMutableArray 值未分配

iphone - 我在其中定义变量(15到20个变量)..Appdelegate文件或.PCH文件或在外部定义它们

iOS、testFlight、app无法联网

ios - 我的xcode项目是否在复制自己?

ios - 如何以编程方式更改detailTextLabel高度

iphone nsarray问题?