我正在尝试通过NSUserDefaults保存我的数据并在表视图中查看它。我已经将四个文本数据设置为数组(dataArray),因此我可以在表视图中查看它。但是我无法将数据加载到表格视图中。我错过了什么吗?
提前致谢。
-(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];
}
答案 0 :(得分:1)
你必须调用[yourUserDefaultObject synchronize];
来保存NSUserDefaults
的状态,但你真的不需要创建4个NSUserDefaults对象,你可以只创建一次然后调用{{ 1}}在同一个实例上,然后是setObject:forKey:
然后,只需设置synchronize
即可在cell.textLabel.text=string;
回调中设置单元格的标签。
答案 1 :(得分:1)
首先同步nsuserdefaults和
您需要分配tableviewcell并将文本分配给文本标签
在cellForRowAtindexpath方法中添加以下代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *string = [dataArray objectAtIndex:indexPath.row];
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text=string;
return cell;
}
答案 2 :(得分:0)
Dude添加以下行,因为您需要在单元格中的某处添加测试。这样就可以显示在tablviewcell.
上如果可能的话,请首先制作数组,而不是在NSUserDefaults
中保存整个数组,这样可以节省您的时间,这是更好的编码方式。
cell.textLabel.text=string;
<强>被修改&GT;&GT;&GT; 强>
UILabel *label;
label = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 50, 40)];
label.text = string;
//或
label.text = @"Hi I am here..";
label.backgroundColor = [UIColor greenColor];
label.textColor = [UIColor whiteColor];
[cell addSubview:label];