Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.


  • If the EO is a fault, calling the EOUtilities method will cause the fault to be resolved, possibly requiring a trip to the db, even though pk info is already present in the fault and the trip to the db is really unneccesary at this point.
  • If the EO has just been inserted and not yet committed, it does not have a pk yet, and the EOUtilities code will throw an exception. And it's not a logical exception corresponding to "no pk yet", but rather some uncaught exception thrown by some surprised Apple code.

Assigning Primary Keys

Wiki MarkupUsually EOF doesn't get around to generating/inserting primary keys until you actually saveChanges() on an EOEditingContext containing newly created about-to-be saved EOEnterpriseObjects.
But sometimes you want to assign a permanent pk as soon as you create the EOEnterpriseObject, not wait until it's actually committed to the db. Here's some code to do that, which, in a given situation, will generate the pk in the same way that EOF would have generated it later, but do it right away. \ [WO:Thanks to Pierre Barnard\]

Code Block
public void _insertObjectWithGlobalID(EOEnterpriseObject eo, EOGlobalID globalID)
   EOEntity entity = EOUtilities.entityNamed(this, eo.entityName());
   EODatabaseContext dbContext = EOUtilities.databaseContextForModelNamed(this, entity.model().name());
   NSDictionary pkDict = primaryKeyDictionaryForDatabaseContextAndEntity(dbContext, entity);

   if (pkDict == null || pkDict.count() != 1)
     NSLog.err.appendln("Failed to generate primary key for entity " + + ", or pk is compound.");
   } else
     Object pk = pkDict.allValues().lastObject();
     globalID = EOKeyGlobalID.globalIDWithEntityName(, new Object[] { pk });

   super._insertObjectWithGlobalID(eo, globalID);

 public static NSDictionary primaryKeyDictionaryForDatabaseContextAndEntity(EODatabaseContext dbContext, EOEntity entity) {
   NSDictionary pk = null;
   try {
     EOAdaptorChannel adaptorChannel = dbContext.availableChannel().adaptorChannel();
     if (!adaptorChannel.isOpen()) {
     pk = (NSDictionary) adaptorChannel.primaryKeysForNewRowsWithEntity(1, entity).lastObject();
   catch (Exception e) {
     NSLog.err.appendln("Can't get primary keys for entity " + + "  " + e);
   finally {
     return pk;