我在我的应用程序中使用 CoreData,它是一对多的关系,我有两个名为folders
and的实体files
。所以一个文件夹可以有很多文件。所以我的第一个视图控制器显示所有文件夹,当单击每个文件夹时,我显示其中存在的文件。
现在,其中存在的所有文件夹和文件都是由用户动态创建的,而不是来自任何数据库或 Web 服务器。
现在我又多了一个视图控制器,我从应用程序委托中打开它,在这里我想显示一些文件。
我知道首先我们应该通过managedObjectContext
,它将在应用程序委托中声明
ViewController *View = [[ViewController alloc]initWithNibName: @"ViewController" bundle:nil]
View.managedObjectContext = self.managedObjectContext;
所以如果我们只是通过managedObjectContext
,我们可以访问文件实体对象,或者我们也必须传递文件实体对象。
现在如您所知,我有两个实体,称为Folder
和File
,现在要访问存储在任何文件夹中的文件,我就是这样做的。
NSMutableArray *filesArray = [self.folder.file mutableCopy];
但是现在,我想在anyView中显示我想要的文件,可以二三导航后打开,也可以直接从appDelegate.m打开。
非常清楚,我的问题是如何做到这一点?即我怎样才能从AppDelegate
.
基于以下答案编辑。我以这种方式创建了一个 fetchResultsController
- (NSFetchedResultsController *)fetchedResultsController {
if (m_fetchResultsController != nil) {
return m_fetchResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"File" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"alarm" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"alarm!= nil"]];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
aFetchedResultsController.delegate = self;
self.fetchResultsController = aFetchedResultsController;
NSError *error = nil;
if (![self.fetchResultsController performFetch:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return m_fetchResultsController;
}
在 ViewDidLoad 中,我是这样写的
- (void)viewDidLoad
{
[super viewDidLoad];
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) {
// Update to handle the error appropriately.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
exit(-1); // Fail
}
NSMutableArray *alarms = [[self.fetchResultsController fetchedObjects]mutableCopy];
NSLog(@"alarmsCount:%d",[alarms count]);
}
问候兰吉特。