我按照建议使用uiManagedDocument单例:http://adevelopingstory.com/blog/2012/03/core-data-with-a-single-shared-uimanageddocument.html
文件由fetchedResultsController访问并显示在tableViewController中。
+ (DocumentHandler *)sharedDocumentHandler
{
static dispatch_once_t once;
dispatch_once(&once, ^{
_sharedInstance = [[self alloc] init];
});
return _sharedInstance;
}
- (id)init
{
self = [super init];
if (self) {
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"ElphiDB"];
self.document = [[UIManagedDocument alloc] initWithFileURL:url];
[self.logger log:@"DocumentHandler Initializing document"];
// Set our document up for automatic migrations
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
self.document.persistentStoreOptions = options;
}
return self;
}
- (void)performWithDocument:(OnDocumentReady)onDocumentReady
{
void (^OnDocumentDidLoad)(BOOL) = ^(BOOL success) {
onDocumentReady(self.document);
[self.logger log:[NSString stringWithFormat:@"performWithDocument success=%d",success]];
};
if (![[NSFileManager defaultManager] fileExistsAtPath:[self.document.fileURL path]]) {
[self.document saveToURL:self.document.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:OnDocumentDidLoad];
} else if (self.document.documentState == UIDocumentStateClosed) {
[self.document openWithCompletionHandler:OnDocumentDidLoad];
NSLog(@"DocumentHandler performWithDocument Open:%@",[self.document description]);
} else if (self.document.documentState == UIDocumentStateNormal) {
OnDocumentDidLoad(YES);
NSLog(@"DocumentHandler performWithDocument state normal");
}
if (self.document.documentState != UIDocumentStateNormal) {
[self.logger log:[NSString stringWithFormat: @"DocumentHandler problem-%@",[self.document description]]];
}
}
//在tableViewController中
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
RootNavigationController *rootNC=(RootNavigationController*)self.navigationController;
if (!self.plugDocument) {
[[DocumentHandler sharedDocumentHandler] performWithDocument:^(UIManagedDocument *document) {
[self.logger log:[NSString stringWithFormat:@"PlugsTVC VWA - call documentHandler doc=%@",document]];
self.plugDocument=document;
self.plugFetcher.document=document;
[self setupFetchedResultsController];
[self fetchPlugDataIntoDocument:document];
}];
}else{
[self.logger log:[NSString stringWithFormat:@"PlugsTVC VWA doc=%@ does exist",self.plugDocument]];
[self fetchPlugDataIntoDocument:self.plugDocument];
}
}
该应用程序在6.0模拟器上正常工作,但在设备上,该表为空,文档显示问题,UIDocumentStateSavingError或UIDocumentStateEditingDisabled。我不知道是什么原因可能导致手机与模拟器的运行方式不同