我正在尝试通过 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/