On 2011 Sep 02, at 19:01, Trygve Inda wrote:

> What is the best way to do this? Do I need to add an observer to every
> object in the array (there are about 8,000 of them).

If you want to use KVO, yes.  I recall some sample code, written by mmalc.  I 
forgot if it was on stepwise.com (which means it's no longer available) or on 
developer.apple.com.  I think the concept is explained in Apple's KVO 
Programming Guide or whatever.

Now, the reason why my memory fails me is because I don't do it this way.  When 
I find myself needing to do gymnastics like that with KVO, I use old-fashioned 
NSNotification/Center/Queue instead.  There are still gymnastics, but maybe 
only half as much.  Most importantly, when a observer is going away, you can 
remove all of its observations with one line of code, invoking 
-[NSNotificationCenter removeObserver:].  If I recall correctly, with KVO you 
need to do careful accounting and remove each key path of each observed object. 
 Any mistakes and you'll get KVO observations sent to dead objects; at least an 
exception and often a crash.  No matter how few bugs you produce in an average 
day, you're going to have relatively fewer of them with one line of code.  
There is still the matter of where to put that line of code, because -dealloc 
is often too late, but you have the same issue KVO, and if this business was 
easy, everybody would be in it :))

In your particular case, you'd have your observer register for a notification 
named, for example "TrygveMyObjectWasMarked", and post this notification in an 
override of -[MyObject setIsMarked:].

> How can I best achieve this so that I get passed the changed MyObject
> (immediately after it changes).

Pass it as the notification object or in the userInfo.  Your desire to have it 
happen "immediately" is another topic.  To get some control over "how fast is 
immediate", you can use NSNotificationQueue and adjust the posting style.  If 
performance becomes an issue, careful coalescing of notifications can usually 
fix it.

I'll be interested to see if anyone posts any other ideas, or disadvantages of 
my design pattern which I've overlooked.

_______________________________________________

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