How to make KVO setup persistent?
How to make KVO setup persistent?
- Subject: How to make KVO setup persistent?
- From: "Arthur C." <email@hidden>
- Date: Thu, 20 Jul 2006 18:13:48 +0200
In my application I have two sets of objects, which can be modelled by a
database with separate object entities called Person and Age.
Person and Age both have a property called "index" used for sorting and to
see which age belongs to a given person.
Now what I want is that Age's property "age" gets changed automatically
whenever I change Person's property "yearofbirth". Assume there is no
binding between Person and Age (although I am interested in both situations;
binding / no binding).
A solution for this using key-value observing is as follows:
@implementation Person
- (void) awakeFromInsert
{
static int localIndex = 0; // ignore the incorrect value at program restart
NSManagedObjectContext * managedObjectContext = [[NSApp delegate]
managedObjectContext];
[self setIndex: [NSNumber numberWithInt: localIndex]];
Age * myAge = [NSEntityDescription insertNewObjectForEntityForName: @"Age"
inManagedObjectContext: managedObjectContext];
[myChineseAge setIndex: [NSNumber numberWithInt: localIndex++]];
[self addObserver:myAge forKeyPath:@"yearofbirth"
options:NSKeyValueObservingOptionNew context:managedObjectContext];
}
@implementation Age
- (void) observeValueForKeyPath:(NSString *) keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqual:@"yearofbirth"])
{
[self setAge:[NSNumber numberWithInt: (2006 - [[change objectForKey:
NSKeyValueChangeNewKey] intValue])]];
}
}
This works OK when the program is first started (empty), but when it is
restarted the objects are reloaded with no KVO setup present.
What is the way to make the KVO setup persistent?
I have tried writing an applicationDidFinishLaunching method where you can
fetch all objects and setup KVO, but without success. The fetched objects
even seem to get deallocated and fetched again after this method has been
called.
My guess is that an awakeFromFetch method is needed analogous to the
awakeFromInsert above, but I don't see how that should be done.
Best regards,
Arthur C.
_________________________________________________________________
MSN Search, for accurate results! http://search.msn.nl
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden