我有一个从远程数据库中获取的字符串列表,它们显示正常。然后,当我添加一个字符串时,新的字符串被添加到数据库中,但是当它出现在屏幕上时,它出于某种原因显示第一个项目的值,即第一个和最后一个项目。 / p>
这是我正在做的事情:
// CREATING EACH CELL IN THE LIST
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"business";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17];
cell.textLabel.numberOfLines = 0;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
}
cell.textLabel.text = [cellTitleArray objectAtIndex:indexPath.row];
// CLOSE THE SPINNER
[spinner stopAnimating];
// return the cell for the table view
return cell;
}
当从数据库中检索数据时,我就是这样做的:
dispatch_sync(dispatch_get_main_queue(), ^{
items_array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if(!error){
[self loadTitleStrings];
}
[self.itemList reloadData];
});
这是名为
的loadTitleStrings-(void)loadTitleStrings
{
if(!standardUserDefaults)
standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *is_private = [standardUserDefaults objectForKey:@"is_private"];
if(!cellTitleArray)
{
cellTitleArray = [NSMutableArray array];
}
for(NSDictionary *dictionary in items_array)
{
NSString *tcid = [dictionary objectForKey:@"comment_id"];
[theArray addObject:tcid];
NSString *string;
if(!is_private || [is_private isEqualToString:@"0"])
{
string = [NSString stringWithFormat:@"%@: %@", [dictionary objectForKey:@"first_name"], [dictionary objectForKey:@"comment"]];
}
else
{
string = [NSString stringWithFormat:@"%@", [dictionary objectForKey:@"comment"]];
}
[cellTitleArray addObject:string];
}
}
是否有人能够告诉为什么最后一项显示的是第一项?我真的很难过!
谢谢!
答案 0 :(得分:1)
我猜cellTitleArray是一个实例变量?如果是这样,第二次调用loadTitleStrings(在将新字符串添加到远程数据库并再次获取所有字符串之后),cellTitleArray将是您当前使用的字符串。也许你再次添加所有字符串。如果是这种情况,可以在-loadTitleStrings中的foreach循环之前添加[cellTitleArray removeAllObjects]。
而且,也许在你的第二个字符串中发生了一些错误。我不认为做你的代码是个好主意:
items_array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if(!error){
[self loadTitleStrings];
}
你传递了一个nil到error参数,当然错误将是nil。当错误发生时,您无法得到通知。试试看是否有错误:
NSError *error = nil;
items_array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if(!error){
[self loadTitleStrings];
} else {
NSLog(@"%@",error);
}