aahrens
aahrens

Reputation: 5590

NSManagedObject passed to ViewController Does Reflect All Updates

In my first view controller what I'm doing is setting up a NSManagedObjectContext from a UIMangedDocument in my viewDidLoad

@property(strong, nonatomic) NSManagedObjectContext *managedObjectContext;

- (void)viewDidLoad
{
     NSURL *filePath = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
     filePath = [filePath URLByAppendingPathComponent:@"Locations"];
     UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:filePath];

    //Create if it doesn't exist
     if (![[NSFileManager defaultManager] fileExistsAtPath:[filePath path]]) {

        //Async save
        [document saveToURL:filePath forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
             if (success) {
                self.managedObjectContext = document.managedObjectContext;
             }
         }];
    } else if (document.documentState == UIDocumentStateClosed){
        [document openWithCompletionHandler:^(BOOL success){

             //Open it, don't need to refetch stuff
             if (success) {
                self.managedObjectContext = document.managedObjectContext;
             }
         }];
     } else {
         self.managedObjectContext = document.managedObjectContext;
     }
 }

Then I insert a new object via a category method on my NSMangedObject subclass

[Location createLocationWithName:@"Maui" inManagedObjectContext:self.managedObjectContext];

Which just calls this code

Location *location = [NSEntityDescription insertNewObjectForEntityForName:@"Location" inManagedObjectContext:managedObjectContext];
[managedObjectContext save:nil];

Now the problem I'm having is when I segue to a new ViewController that has a public NSManagedObjectContext property and set it to this managedObjectContext in prepareForSegue the NSFetchedResultsController in the destinationViewController doesn't pick up this change right away. After I navigate back a forth a few times it eventually sees the Location Maui I created above. Any ideas why inserting a new Object into the managedObjectContext and then passing it to another view controller doesn't reflect that change?

Any insight is greatly appreciated.

Upvotes: 0

Views: 86

Answers (1)

Mundi
Mundi

Reputation: 80273

If you creation method contains the name you should at least also set this attribute (otherwise it will be lost). So second line of your creation implmentation:

location.name = name; // name is passed to the method

In order to ensure that the fetched results controller of the second view controller is updated immediately, you could set the cacheName to nil when creating the FRC. If you have lots of records and think you need the cache, you can do this in viewWillAppear:

[self.fetchedResultsController performFetch:&error];

Upvotes: 0

Related Questions