2012-05-25 39 views
0

嗨,大家好,我收到这个错误,当我尝试添加到一个空表视图:插入行0到部分0,但更新后0节只有0行。有什么想法吗?表视图插入错误

dispatch_queue_t fetchQ = dispatch_queue_create("Blog Fetcher", NULL); 
    dispatch_async(fetchQ, ^{ 
         //pull this call out to Blog+twitter later saving should only take 
         //place in the model! 

         [document.managedObjectContext performBlock:^ 
         { 
          NSArray* resultsArray = [self.tweets objectForKey:@"results"]; 

          for (NSDictionary* internalDict in resultsArray) 
          { 

          User *user = [NSEntityDescription 
                insertNewObjectForEntityForName:@"User"inManagedObjectContext:self.context]; 
           user.username =[internalDict objectForKey:@"from_user_name"]; 
           [self.context save:nil]; 

           self.list = [self.list arrayByAddingObject:user]; 
           NSLog(@" indexpath set here %i",self.list.count-1); 
           NSIndexPath *newIndexpath =[NSIndexPath indexPathForRow:self.list.count-1 inSection:0]; 
           [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexpath] withRowAnimation:UITableViewRowAnimationAutomatic]; 
          } 
         }]; 

       }); 
      dispatch_release(fetchQ); 

} 
+0

正如@JefferyThomas所暗示的,UIKit对象(例如tableview)的所有更新都必须从主线程完成。另外,确保所有的核心数据保存都在同一个线程上完成(不要在主线程**和**这个线程上执行)。 – lnafziger

回答

0

我的第一个想法是,你应该派遣更新到主线程。我不确定您的实施细节,但您也可能需要将[self.context save:nil]也移动到主线程。

NSArray* resultsArray = [self.tweets objectForKey:@"results"]; 
NSMutableArray *users = [NSMutableArray arrayWithCapacity:resultsArray.count]; 
NSMutableArray *indexPaths = [NSMutableArray arrayWithCapacity:resultsArray.count]; 
NSInteger row = self.list.count; 

for (NSDictionary* internalDict in resultsArray) 
{ 
    User *user = [NSEntityDescription insertNewObjectForEntityForName:@"User"inManagedObjectContext:self.context]; 
    user.username =[internalDict objectForKey:@"from_user_name"]; 
    [self.context save:nil]; 

    [users addObject:user]; 

    NSLog(@" indexpath set here %i", row); 
    NSIndexPath *newIndexpath =[NSIndexPath indexPathForRow:row inSection:0]; 
    row++; 

    [indexPaths addObject:newIndexpath]; 
} 

dispatch_async(dispatch_get_main_queue(), ^{ 
    self.list = [self.list arrayByAddingObjectsFromArray:users]; 
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexpath] withRowAnimation:UITableViewRowAnimationAutomatic]; 
};