Re: Design Question: Pro & Cons of KVC/KVO
Re: Design Question: Pro & Cons of KVC/KVO
- Subject: Re: Design Question: Pro & Cons of KVC/KVO
- From: "Oleg Krupnov" <email@hidden>
- Date: Thu, 21 Aug 2008 16:22:48 +0300
>> I suspect that it could be way easier, when a property's value
>> changes, to just explicitly send a concise and clearly named message
>> to the subscribed objects,
>
> This is, what is done. The name of the message is
> -observeValueForKeyPath:ofObject:change:context:
Then how is it better than manual "glue code"?
> I think, you want to say, that if one changes a property, he sends a message
> to a central MVC server, which distributes update messages. Correct? Why?
>
No. Actually, the alternative approach that I kept in mind was that
each model object maintains an array of observers (like delegates or
just objects with a declared protocol) to all of which the
corresponding message is sent each time a property of the model object
changes.
For example,
id<MyModelObjectObserver> observer;
MyModelObject* myModelObject;
// subscribe observer
[myModelObject addObserver: observer];
// set some prop
[myModelObject setSomeProp:someValue];
@interface MyModelObject
{
NSMutableArray* m_observers;
id m_someProp;
}
@end
@implementation MyModelObject
- (void)addObserver:(id<MyModelObjectObserver>) observer
{
[m_observers addObject:observer];
}
- (void)setSomeProp:(id)newValue
{
// save new value
m_someProp = newValue;
// notify observers
id<MyModelObjectObserver> observer = nil;
for (observer in m_observers)
{
[observer somePropChanged];
}
}
@end
Is there something terribly wrong with this approach? The dependencies
are encapsulated. In addition, it seems that this approach gives me
more flexibility, say, if newValue is invalid, it can be rejected. Or,
for instance, when the entire MyModelObject gets removed from its
parent model object - in this case there is no property actually
modified, instead, a mutator message is received by the model, but the
observers still need to be notified. Can KVC/KVO monitor the contents
of an array of model objects? And so on. Even though KVC/KVO may
handle these cases too, my intuition tells me there can be cases when
the flexibility of KVC/KVO may run short compared to the manual code.
Anyway, even if I assume that KVC/KVO is at least not worse than
manual code, I don't see any real benefit so far. Except that it
allows me to get the scripting support "for free" (but I'd rather like
the scripting to be separate thing and not get in the way of the model
objects).
Could someone please try to explain me the rationale behind KVC/KVO
once again? :) Thanks
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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:
This email sent to email@hidden