Singleton核心数据方法

时间:2013-01-29 20:13:06

标签: ios uitableview core-data nsfetchedresultscontroller

我正在尝试将单例用于核心数据。 这是核心数据堆栈:

#pragma mark - Core Data stack
- (NSManagedObjectContext *)managedObjectContext {
if (_managedObjectContext != nil) {
    return _managedObjectContext;
}

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel {
if (_managedObjectModel != nil) {
    return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (_persistentStoreCoordinator != nil) {
    return _persistentStoreCoordinator;
}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"MyApp.sqlite"];

NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

return _persistentStoreCoordinator;
}
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

这是我用来保存实体的方法,它可以正常工作

-(void)addFund {

Fund *fund = [NSEntityDescription insertNewObjectForEntityForName:@"Fund" inManagedObjectContext:self.managedObjectContext];

 fund.name = @"Test Name";

 [self.managedObjectContext save:nil];  // write to database
}

当我需要在控制器中显示表格中的项目时,问题就出现了。我创建了一个返回NSFetchedResultsController的方法。可能这是错误。

 -(NSFetchedResultsController*)loadFunds {
//Core data request
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Fund"
                                          inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

fetchRequest.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]];
 NSFetchedResultsController *result = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                    managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil
                                               cacheName:@"Root"];
return result;
}

但是tableview没有返回任何内容(Null):

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

NSInteger numberOfSections = [[[[Singleton sharedSingleton] loadFunds] sections] count];

if (numberOfSections == 0) {
    numberOfSections = 1;
}

return numberOfSections;

}


-(NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
id  sectionInfo = [[[Singleton sharedSingleton].loadFunds sections] objectAtIndex:section];

    return [sectionInfo numberOfObjects];

}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Category Cell";
....
// Configure the cell...
Fund *fund = [[Singleton sharedSingleton].loadFunds objectAtIndexPath:indexPath];
cell.titleLabel.text = fund.name;
....
}

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您需要使用以下方式获取数据:

NSError *error;
[self.fetchedResultsController performFetch: &error];

然后按如下方式重新加载tableview:

[self.tableView reloadData];