Re: properties, threads, and KVO
Re: properties, threads, and KVO
- Subject: Re: properties, threads, and KVO
- From: Chris Hanson <email@hidden>
- Date: Tue, 04 Nov 2008 07:49:02 -0800
On Nov 4, 2008, at 7:20 AM, Karan, Cem (Civ, ARL/CISD) wrote:
KVO is ideal, but I don't know it works across threads.
KVO doesn't do anything special with respect to threads.
Since it's synchronous, that means KVO notifications are delivered in
the thread in which they occur, just as if you had set up the server
to call methods on your client directly.
I know that properties are supposed to default to thread-safe, and I
know that as long as I don’t explicitly specify getter/setter
methods, properties should be KVC/KVO compliant, but I'm not sure if
the above is 100% kosher. Is there anything I should be worried
about?
This term "thread-safe," I do not believe it means what you think it
means. ;)
Properties are by default *atomic*. That means no matter what
multiple threads are doing with an individual property, threads will
either see the "before" or "after" state of the property itself, never
an intermediate state.
What it *doesn't* mean is that you'll always see a consistent state of
*multiple* properties. That's something you'll have to enforce
yourself, either at the per-object or per-object-graph level. The
canonical example is a Person object with atomic givenName and
familyName properties and a fullName property that returns the two as
a single string:
@interface Person : NSObject
@property (copy) NSString *givenName;
@property (copy) NSString *familyName;
@property (readonly) NSString *fullName;
@end
Atomic properties only guarantee that you won't get back a zombie from
any of the above properties. They make no guarantee that fullName
won't be "Cem Hanson" or "Chris Karan."
Furthermore, if anything is observing a Person using KVO, it will
receive change notifications for the Person's properties on the thread
on which the change takes place. It needs to know whether the Person
it is observing can change in an arbitrary thread and be prepared for
that if it can.
The code you posted doesn't really take this into account; it appears
to expect the KVO notification to be delivered "across" threads.
Furthermore, it doesn't do any locking or other synchronization, which
will still be required if both the client and server are dealing with
the same object. It's not something the compiler can be "smart" about
-- you need to handle that yourself.
-- Chris
_______________________________________________
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