After some research I am still unsure on when / how I should create my UIManagedDocument.
@interface ViewController ()
@property (strong, nonatomic) UIManagedDocument *document;
@end
@implementation ViewController
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
NSString *documentName = @"MyDocument";
NSURL *url = [documentsDirectory URLByAppendingPathComponent:documentName];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[url path]];
if (fileExists) {
[self.document openWithCompletionHandler:^(BOOL success) {
NSLog(@"Exsits dont create again");
if (success) [self documentIsReadyCreateAndObject];
if (!success) NSLog(@"cound not open document at %@", url);
}];
}
else {
// create it
[self.document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
NSLog(@"Create it");
if (success) [self documentIsReadyCreateAndObject];
if (!success) NSLog(@"cound not create document at %@", url);
}];
}
}
- (void) documentIsReadyCreateAndObject
{
if (self.document.documentState == UIDocumentStateNormal) {
NSLog(@"document is ready - create obj");
Car *demo = [NSEntityDescription insertNewObjectForEntityForName:@"Car" inManagedObjectContext:self.document.managedObjectContext];
demo.carName = @"xxxxx";
}
else {
NSLog(@"Not ready to go");
}
}
- (void) fetchAndPrint
{
if (self.document.documentState == UIDocumentStateNormal) {
NSLog(@"document is ready - print objs");
NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Car"];
NSArray *results = [self.document.managedObjectContext executeFetchRequest:request error:nil];
for (Car *aLog in results) {
NSLog(@"\nNAME: %@", aLog.carName);
}
}
else {
NSLog(@"Not ready to go");
}
}
@end