3

What is the preferred approach to registering observers on an NSManagedObject (since Core Data "'owns' the lifecycle" of managed objects)?

Am I correct that the way to do this is to listen for NSManagedObjectContextObjectsDidChange-Notification and call addObserver:... for NSInsertedObjectsKey and removeObserver:... for NSDeletedObjectsKey?

orome
  • 45,163
  • 57
  • 202
  • 418

2 Answers2

1

In order to observe MOs throughout their lifecycles, add observers when they come into existence, with awakeFromInsert and awakeFromFetch.

orome
  • 45,163
  • 57
  • 202
  • 418
-1

Yeah, you're correct. Observing the MOs directly will lead to trouble, for reasons you have already posted in your question (within the parentheses).

Enchilada
  • 3,859
  • 1
  • 36
  • 69
  • Actually, I think what I suggested above is wrong. I think the place to add observers is `awakeFromInsert` and `awakeFromFetch`. (Removing them is unnecessary.) – orome Jun 09 '11 at 23:42
  • What actually is it that you want to do? If you want to do something when the MO is created, then sure, awakeFromInsert and awakeFromFetch are your friends. But if you want to observe changes to some random MOs, the above I think is correct. Depends on what you're after. – Enchilada Jun 10 '11 at 07:55
  • I want to observe instances of some MOs throughout their lifecycles, so if I add observers when they come into existence (with `awakeFromInsert` and `awakeFromFetch`), I should be fine. – orome Jun 11 '11 at 12:57