0

I have a number of View Controllers that need to show data from a Core-Data store.

Each of them fetch managed objects from the same context but for some reason the number of managed objects increases when more than once VC has made a fetch?

Can the managedObjects not be shared within the same context and only pointer reference?

Why is the number of managed objects increasing when the View Controllers request the same data?

Code:

- (void) updateCacheWithObject:(Object *)object
{

[self.coreDataSaveQueue addOperationWithBlock:^{

    NSManagedObjectContext *saveContext = [[NSManagedObjectContext alloc] init];
    [saveContext setPersistentStoreCoordinator:[self persistentStoreCoordinator]];

    AudioObject *object = [NSEntityDescription
                             insertNewObjectForEntityForName:@"object"
                             inManagedObjectContext:saveContext];

    [audioObject setValue:object.localPath forKey:@"localPath"];
    [audioObject setValue:object.title forKey:@"title"];
    [audioObject setValue:object.data forKey:@"data"];

    NSError *error;

    // does the psc have a store
    if ([saveContext.persistentStoreCoordinator.persistentStores count] == 0) {
        [saveContext setPersistentStoreCoordinator:[self persistentStoreCoordinator]];
    }

    if (![saveContext save:&error])
    {
        NSLog(@"Couldn't save: %@", [error localizedDescription]);
        NSLog(@"Error user info dictionary is %@", [error userInfo]);
    }
}
some_id
  • 29,466
  • 62
  • 182
  • 304
  • 1
    A fetch request does not create objects. Can you show the code of the fetch request? – Martin R Mar 15 '13 at 21:13
  • I perfectly agree with @MartinR. If you have some code that at startup populate the store, that could be the origin of the problem. Provide some code if possible. – Lorenzo B Mar 17 '13 at 15:41

1 Answers1

0

What you've shown is not a fetch. It's an insert (specifically insertNewObjectForEntityForName:inManagedObjectContext:). The class you want is NSFetchRequest.

I also see that, for some reason, you're assigning self.persistentStoreCoordinator toe saveContext's PSC twice, once in line 7 and once about 10 lines from the bottom.

Hal Mueller
  • 7,019
  • 2
  • 24
  • 42
  • I think you missed the question. I provided the code in response to flexaddicted's comment "If you have some code that at startup populate the store, that could be the origin of the problem. Provide some code if possible." Also, the second assignment has actually helped my in some multithreaded environments, where a strange error occurred randomly stating the context has no persistent stores. – some_id Mar 27 '13 at 00:09
  • You're right. I thought you were responding to MartinR's request to post the fetch code. Can we see that? – Hal Mueller Mar 27 '13 at 00:28
  • This is solved already, and seemed to be a threading issue and unsynced contexts. – some_id Mar 27 '13 at 01:08