我有一个简单的基于 UIManagedDocument 的核心数据应用程序。我是在 iOS 中编程的新手,我几乎没有开始使用它,我被困住了。我将 People NSManagedObjects 存储在核心数据中。当我第一次启动应用程序时,那里没有任何条目,但是如果我向上滑动一个模态 VC 并关闭它,它们就会神奇地出现。我的设计大致基于 iTunes U/Sanford 课程中的“Photomania”应用程序,但使用单例 CoreDataStore 对象来处理获取 managedObjectContext。这是我的 CoreDataStore 的代码:
+ (CoreDataStore *)sharedStore
{
static CoreDataStore *sharedStore = nil;
if (!sharedStore)
sharedStore = [[super allocWithZone:nil] init];
return sharedStore;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
return [self sharedStore];
}
- (NSManagedObjectContext *)getContext
{
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"dbDocument"];
UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:url];
if (![[NSFileManager defaultManager] fileExistsAtPath:[url path]]) {
NSLog(@"No file exists...");
[document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
NSLog(@"Document saveForCreating completionHandler invoked. Success: %hhd", success);
if (success) {
self.managedObjectContext = document.managedObjectContext;
NSLog(@"Got context for created file!!");
}
}];
} else if (document.documentState == UIDocumentStateClosed) {
NSLog(@"Document state is closed. documentState == %u", document.documentState);
[document openWithCompletionHandler:^(BOOL success) {
NSLog(@"Document opening success: %hhd", success);
if (success) {
self.managedObjectContext = document.managedObjectContext;
NSLog(@"Got context for now-opened file!!");
}
}];
} else {
self.managedObjectContext = document.managedObjectContext;
NSLog(@"Got context for already-opened file!!");
}
return self.managedObjectContext;
}
以下是 PeopleListViewController 的代码:
- (void)setManagedObjectContext:(NSManagedObjectContext *)managedObjectContext
{
_managedObjectContext = managedObjectContext;
if (managedObjectContext) {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"name"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)]];
request.predicate = nil; // all Persons
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:nil];
} else {
self.fetchedResultsController = nil;
}
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if (!self.managedObjectContext)
[self setManagedObjectContext:[[CoreDataStore sharedStore] getContext]];
}
这是启动后立即出现的结果:
这是模态VC:
这是在关闭模态 VC 之后(点击取消):
我尝试在 managedObjectContext 上使用 performFetch,甚至将其延迟到 Core Data 文档报告它已打开之后。没有任何效果。任何帮助将不胜感激。