Вопрос

I have class A (subclass of NSManagedObject) that has a property of class B (also subclass of NSManagedObject), the property is @synthesize not @dynamic, there is no relationship between A and B in my model, I just want that A will keep a reference to a B object while he(A) is alive.
(When I first fetch object A from db, his B property is null)

I Override the B property getter, so when first called he will fetch the B object from db.

Now do I need to retain the fetch result of B?
I think I heard that it is not a good idea to retain objects that the NSManagedObjectContext manage.

Это было полезно?

Решение

There's no problem with retaining NSManagedObject — go ahead and do it. The only thing to be careful about is if you're holding onto an object and it is getting deleted. Then you have a reference to an object, but if you try to read or set any value of it, you'll get an exception. Because this is tricky to update, Core Data does delete propagation for you when you're using Core Data relationship.

So, as stated above: Use relationships. There's nothing wrong with having multiple relationships between A and B. You just need to have the corresponding inverse relationships, too.

For example, you can do something like this:

Person
  favoriteBook (to-1, inverse is favoriteByPersons)
  authoredBooks (to-many, inverse is authors)

Book
  authors (to-many, inverse is authoredBooks)
  favoriteByPersons (to-many, inverse is favoriteBook)

Let Core Data do the heavy lifting for you. Relationship management is one of the things Core Data is really good at. Don't try to copy that yourself.

Другие советы

You should clearly go with a to-one relationship between A and B. This is what Core Data is set up to manage for you. It's simpler, more robust, and you do not have to worry about memory issues.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top