Obj-C: NSManagedObject init within a related object's awakeFromInsert causes EXC_BAD_ACCESS

Discussion in 'iOS Programming' started by moonman239, Jan 6, 2016.

  1. moonman239 macrumors 68000

    Mar 27, 2009
    I have two entities and two NSMangedObject subclasses. One entity, which we'll call Alice, has a to-many relationship with the other entity - which we'll call Bob. When an Alice object is created, it needs to have an associated Bob object so that my other code works.

    Here's the code from my Alice subclass's awakeFromInsert method:
        [super awakeFromInsert];
        Bob *bob = [[Bob alloc] initWithEntity:[self entity] insertIntoManagedObjectContext:[self managedObjectContext]];
        [self addPlacesObject:bob];
  2. Mascots, Jan 7, 2016
    Last edited: Jan 7, 2016

    Mascots macrumors 65832


    Sep 5, 2009
    Which is causing the BAD_ACCESS exception? At some point, you're accessing memory that either hasn't been allocated or has already been deallocated - it'll be faster to use a breakpoint to see exactly what memory doesn't exist.

    If it's related to the code you've posted, it may be the [self entity], though I could be wrong because I believe both of the properties you are accessing should be available by the time awakeFromInsert is being called since they are required for the initializer. If you can verify those aren't set then I may be able to suggest other things that cause that problem - Otherwise, the error is probably being propagated by some kind of indirect response from elsewhere in your app which is not fun.

    Maybe initializing your subclass an alternate way may help (copy with care, it's been awhile since I've written objc ;]):

    bob = [NSEntityDescription insertNewObjectForEntityForName:@"Bob" inManagedObjectContext: [self managedObjectContext]];
    I also meant to say that I personally handle all relationship automation in willSave since I can guarantee the entities are normalized before being placed into the database. I find the end values matter more than the starting values, and if I were to require a relationship in the entity prior to working with it, I'd probably write a custom initializer in which my related entity has to be created in the same context (note: not saved) and passed with it to get the dependent one.

Share This Page