4

Here is a brief sequence that involves a Core Data stack with an (initially empty) NSManagedObjectContext and a NSPersistentStoreCoordinator with two NSPersistentStores:

Player *player = [NSEntityDescription insertNewObjectForEntityForName: @"Player" 
                                               inManagedObjectContext: context];
player.playerID = playerID;
// (1) [context assignObject: player toPersistentStore: secondStore];

NSFetchRequest *requestForPlayer = [NSFetchRequest fetchRequestWithEntityName: @"Player"];
requestForPlayer.predicate = [NSPredicate predicateWithFormat: @"playerID == %@", playerID];
NSAssert(requestForPlayer.affectedStores == nil, nil); // inits to nil
// (2) requestForPlayer.affectedStores = @[ secondStore ];

players = [context executeFetchRequest: requestForPlayer error: &error];

This fetches one player. If I uncomment (2) (i.e. involve the second store) it fetches zero (sic!) players. If I uncomment also (1) it fetches again one player.

So it seems as if the behavior NSFetchRequest returns unsaved NSManagedObjects only if

  1. either affectedStores is nil and those objects have not been assigned to any store
  2. or affectedStores is not nil and those objects have been assigned to an affected store

Is this indeed the case and if so, where is this documented by Apple?

Drux
  • 11,992
  • 13
  • 66
  • 116
  • I can't find it documented either. It's interesting that `NSFetchRequest` inherits from `NSPersistentStoreRequest` and yet you throw it at a MOC. Anyways: you *have* seen that affectedStores inits to nil and not the PSC's first/last store/whatever? I'm not sure if you imply that intentionally in #1, or assume it. – stevesliva Mar 10 '15 at 23:46
  • @stevesliva 1. I guess an important reason for `NSFetchRequest` inheriting from `NSPersistentStoreRequest` is its convenient use as sibling of `NSSaveChangesRequest` in `NSIncrementalStore`'s `executeRequest:withContext:error:`. 2. Yes I have seen that (unless there was a mistake). The (to me) somewhat surprising thing is that in this Q's context `affectedStores == nil` apparently denotes "first/last/whatever" if there is only store one but "none of these" if there are several stores. – Drux Mar 11 '15 at 02:46

0 Answers0