EXC_BAD_ACCESS:核心数据,NSFetchedResultsController和numberOfRowsInSection

时间:2011-01-29 05:09:53

标签: objective-c ios core-data

在我的UITableViewController类中,我有一个NSFetchResultsController的getter函数

-(NSFetchedResultsController*) fetchedResultsController {

    if (_fetchedResultsController == nil) {
        FlipPadAppDelegate* app = (FlipPadAppDelegate*) [[UIApplication sharedApplication] delegate];
        NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init];
        [fetchRequest setEntity:
            [NSEntityDescription entityForName:@"FundClass" inManagedObjectContext:[app managedObjectContext]]];
        NSSortDescriptor* sortdesp = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortdesp]];

        [fetchRequest setFetchBatchSize:20];

        _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
                                                                       managedObjectContext:[app managedObjectContext]
                                                                         sectionNameKeyPath:nil 
                                                                                  cacheName:@"_Stock"];


        _fetchedResultsController.delegate = self;  
        [fetchRequest release];
        [sortdesp release];

        NSError *error;
        if (![[self fetchedResultsController] performFetch:&error]) {
            // Handle error
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

        }
    }

    return _fetchedResultsController;

}

不知何故,当应用程序运行到此时,

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    id <NSFetchedResultsSectionInfo> sectionInfo = [[[self fetchedResultsController] sections] objectAtIndex:section];
    NSLog(@"numberOfRowsInSection %@", [sectionInfo numberOfObjects]);
    return [sectionInfo numberOfObjects];

}

它会触发EXC_BAD_ACCESS

sqllite数据库中有两条记录。

为什么例外?是因为我将sectionNameKeyPath设为零吗?或者因为我没有将视图的dataSource设置为此控制器?

1 个答案:

答案 0 :(得分:4)

因为您正在记录对象@“numberOfRowsInSection%@”并且numberOfObjects是一个int:

@property (nonatomic, readonly) NSUInteger numberOfObjects

使用@“numberOfRowsInSection%i”代替。