无法获取tableView中的单元格数

时间:2013-09-13 06:06:19

标签: ios objective-c uitableview core-data nsfetchedresultscontroller

我有一个主tableViewController,触摸一个按钮self.navigation将推送addItem viewController,点击保存self.navigation并弹出添加VC,然后我们回到主要的一个,我成功添加并保存,也获取,但是当提取数量的单元格时,数字返回0,继承方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

id <NSFetchedResultsSectionInfo> secInfo = [[self.fetchedResultsController sections]     objectAtIndex:section];
NSLog(@"No. of cells determined: %lu", (unsigned long)[secInfo numberOfObjects]);
return[secInfo numberOfObjects];

}

NSLog给了我0,问题是什么,这让我很头疼。

这是获取请求:

- (NSFetchedResultsController*) fetchedResultsController {

// Fetch Request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Goal"
                                          inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title"
                                                               ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];




// setting _fethcedResultsController
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                managedObjectContext:self.managedObjectContext
                                                                  sectionNameKeyPath:nil
                                                                           cacheName:nil];




// setting _fetchedResultsController to self
_fetchedResultsController.delegate = self; // for the tableview updating thing



// Thats it
return _fetchedResultsController;

}

请注意,当我检查物品时,它不是零:

// fetching all items to check how many of them exists
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity: [NSEntityDescription entityForName:@"Goal"
                                     inManagedObjectContext:self.managedObjectContext]];
NSManagedObjectContext *moc = self.managedObjectContext;

NSError *fetchError = nil;
NSArray *goals = [moc executeFetchRequest:fetchRequest error:&fetchError];

NSLog(@"No. of goals: %lu", (unsigned long)[goals count]);
// end of check for items

1 个答案:

答案 0 :(得分:1)

我忘记了这行代码:

if (_fetchedResultsController != nil) {
    return _fetchedResultsController;
 }
方法

中的

- (NSFetchedResultsController*) fetchedResultsController; 

所以在我做之前,应用程序总是创建新的fetchedResultsController并覆盖旧的。