0
votes

I have a few questions around the creation of managed object contexts in core data in my app if you can help out please...

To simplify, say my app an entity Street and another entity House. Each Street object has various attributes, including an attribute houseList (NSArray) (which is of Transformable type) of House objects. If I do not introduce the House entity and have Core Data only for Street, everything works fine and I'm able to save the context, load all House objects in a given street, etc.

But the moment I create an entity for House (I am saving it in the same MOC as Street) and run setHouseList, the next time I launch the app, I get the usual error "CoreData: error: Failed to call designated initializer on NSManagedObject class 'House'". Following questions that I have around this...

  1. Does this situation also mean that I have different threads at play? Apologies for the ignorance but per my understanding, there is no background thread here doing a parallel update, so ideally these are not separate threads, thus I should not be requiring a separate managed object context.

  2. I even tried declaring a new MOC property in the app delegate and passed that through to the view controller where setHouseList is called, and then also saved any House objects in this new MOC. That hasnt helped either and I get the same error.

  3. I'm suspecting I might have to use ObjectID whilst calling setHouseList if I use a new MOC, but somehow cant get my head around how to do that... I've further gone through the https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/Concurrency.html and https://www.cocoanetics.com/2012/07/multi-context-coredata/ links but not making any progress... any inputs would be much appreciated!

Thanks!

1
Without any code it's difficult to anwer this question. How do you create you House MO? - RFG
You should not use an Array of Houses. Use relations instead. - Thallius
Thanks @ClausBönnhoff ... yes using relationships fixed the problem for me! Thanks...! - vikram17000

1 Answers

2
votes

You should really set up a to-many relationship between House and Street entities, where one Street can have many Housees associated with it.

If order is important (which I would imagine it wouldn't be), then you can model the relationship as an NSOrderedSet, though NSSet sounds like it would be just fine in this case.

class Street: NSManagedObject {
    @NSManaged var houses: NSOrderedSet
}

class House: NSManagedObject {
    @NSManaged var street: Street
}

Then, when you're creating the objects, set the street property on the House and add the House to the set of houses on the Street.

func addHouse(house: House) {
    let houses = self.mutableSetValueForKey("houses")
    houses.addObject(house)
}

Core data will handle there rest from there.