On 2009 Oct 17, at 04:55, Joshua Garnham wrote:

Could I sub class NSManagedObject to make it observe objects as they are added or fetched?

Well, first of all, let me rephrase your question. What you're suggesting is to add an observer of the "name" property as objects are inserted or fetched.

Now, I'm not sure if you should do that, or observing the tree controller as recommended by Kyle. However, since I don't have a tree controller in a project of mine, I've kind of done what you suggested.

So, if you're sure you want to do it this way, here goes....


Yes, any full-featured Core Data app eventually needs to subclass NSManagedObject. I use two levels of inheritance:

   NSManagedObject
      MyWhistlesAndBellsManagedObject
          Employee
          Department
          etc.

then add the following code to make it observe objects as they are added or fetched?

- (void) awakeFromFetch {
[self addObserver:[NSApp delegate] forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
}

- (void) awakeFromInsert {
[self addObserver:[NSApp delegate] forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
}

Yes. I usually do this by writing an -initializeCommon method that adds all my observers, and other stuff. Then -awakeFromFetch and - awakeFromInsert both invoke -initializeCommon.

But then don't forget to implement -didTurnIntoFault in your NSApp's delegate, and in that implementation, removeObserver (and also don't forget to invoke super).

But how would I trigger an action when the name property changes?

If I understand correctly, this is a basic KVO question. The short answer is to implement

-observeValueForKeyPath:ofObject:change:context:

A better answer is that you should have already learned that by reading Apple's KVO Programming Guide:

http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html

And then, for even further reading,

http://mikeash.com/?page=pyblog/key-value-observing-done-right.html

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to