2012-12-17 48 views
-1

我有從遠程數據庫中獲取的字符串列表,它們顯示正常。然後,當我添加一個字符串時,新的字符串被添加到數據庫中,但是當它顯示在屏幕上時,它出於某種原因顯示了第一個和第二個項目中的第一個項目的值。ios - 無法弄清楚爲什麼項目列表顯示添加新項目時第一個和最後一個點的第一個項目的值

下面是我在做什麼:

// 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]; 
    } 
} 

任何人都可以知道爲什麼最後一項顯示的值是第一個?我真的很難過!

謝謝!

回答

1

我猜cellTitleArray是一個實例變量?如果是這樣,第二次調用loadTitleStrings(在將新字符串添加到遠程數據庫並再次獲取所有字符串後),cellTitleArray將是您當前使用的字符串。也許你再次添加所有的字符串。如果出現這種情況,可以在-loadTitleStrings的foreach循環之前添加[cellTitleArray removeAllObjects]。

而且,也許在你的第二個字符串中發生了一些錯誤。我不認爲這是一個好主意,做的代碼:

items_array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 

if(!error){ 
    [self loadTitleStrings]; 
} 

你通過了零到錯誤的參數,當然還有誤差爲零。發生錯誤時,您無法通知。試試看看是否有錯誤:

NSError *error = nil; 
items_array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; 

if(!error){ 
    [self loadTitleStrings]; 
} else { 
    NSLog(@"%@",error); 
} 
相關問題