The World’s Leading Microsoft .NET Magazine
   
 
The .NET Addict's Blog

My Top Tags

                                                           

My RSS Feeds








I heart FeedBurner

Latest Diggs - Programming

Computers Blogs - Blog Top Sites

Site Hits

Total: 2,817,121
since: 19 Jan 2005

Batch observing an entire array of objects in Cocoa (or - how I learned to love Categories)

posted Wed 21 Mar 07

In my last blog post on Cocoa programming, I mentioned my new-found love for the NSUndoManager class. While I still love that class, something else interesting happened while working on that sample. A reader who knows far more about Cocoa than I do pointed out that instead of using my fast enumerator:

for (Person *p2 in employees)
{
    [self startObservingPerson:p2];
}

I could actually use a different method that will batch-add an observer to an entire array of objects. Then it became a question of dealing with the unwieldy syntax of that method. Basically that method is really flexible and lets me observe subranges within an array - and I only wanted to observe the entire array. This is when the idea was suggested by that very same astute reader that I could create an extension to NSMutableArray that contains a wrapper for this method call. So, here's the extension implementation to NSMutableArray:

@implementation NSMutableArray (ObserverExtension)

- (void)addObserver:(id)observer
    toAllObjectsForKeyPath:(NSString *)keyPath
    options:(NSKeyValueObservingOptions)options
    context:(void *)context
{
    NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:
        NSMakeRange(0, [self count])];

    [self addObserver:observer
       toObjectsAtIndexes:indexes
       forKeyPath:keyPath
       options:options
       context:context];

}

This is ridiculously cool, because now I can invoke this method on an NSMutableArray without ever having subclasses NSMutableArray. The following is my replacement for the fast enumerator I had previously:

[employees addObserver:self
    toAllObjectsForKeyPath:@"personName"
    options:NSKeyValueObservingOptionOld
    context:NULL];
[employees addObserver:self
    toAllObjectsForKeyPath:@"expectedRaise"
    options:NSKeyValueObservingOptionOld
    context:NULL];

Granted, you won't see this in the chapter where you write this code - you only get to invoke this code when you get to Aaron's archiving chapter..but when you do, and you're using the new improved batch-observe stuff here, you'll probably be like me and get a little weepy and emotional at how unbelievably cool this stuff is.

tags:                  

links: digg this    del.icio.us    technorati    reddit




1. Mike Abdullah left...
Wed 21 Mar 07 9:08 am :: http://mikeabdullah.net

Glad the code was of use to you in the end then Kevin :)

One thing I am curious about though is why you made this a category on NSMutableArray? Since NSMutableArray is a subclass of NSArray, if you create the category on NSArray instead, that method becomes available for instances of either class.


2. Kevin Hoffman left...
Wed 21 Mar 07 9:10 am

No particular reason. I knew ahead of time that it was an NSMutableArray, so that's why I made it a category on that. As you said, I could just as easily have made it an NSArray category and had it apply to a wider range of arrays.


3. Martin Wennerberg left...
Fri 23 Mar 07 2:26 am :: http://www.norrkross.com

Be aware though that there is a danger to adding categories to others code as you don't know if you're overriding some private method or a future public method. To be safe you could name your new method with a prefix, as with all global symbols.


4. Raymond Lutz left...
Fri 23 Mar 07 10:28 am :: http://homepage.mac.com/lutzray/

Just echoing Martin post about objc categories name clashes... Read bbum post at

C# 3.0: Now with Categories!


5. Kevin Hoffman left...
Fri 23 Mar 07 1:17 pm

Yes, obviously I could have used prefixes to avoid name clashes.. As it was just a quick "let's see if this works" sample, I didn't really spend that much time on prefixing.

Also, as a C# developer, I hate using capital-letter prefixes... I'm so used to namespaces that I sorely miss them in Objective-C.


Tag Related Posts

Apple drops the iPhone NDA for Released Software

Wed 01 Oct 08 3:54 P GMT-05
tags:          

Cappuccino, Objective-J, and You

Wed 10 Sep 08 6:14 P GMT-05

So I'm in the LA Times ;)

Wed 27 Aug 08 2:51 P GMT-05
tags:                  

MobileMe vs. Live Mesh Throwdown - Round 1

Wed 16 Jul 08 10:33 A GMT-05

Building Model Classes in C# and Cocoa

Sun 15 Jun 08 3:13 P GMT-05
tags:            

MobileMe vs. Live Mesh - Round 1

Wed 11 Jun 08 12:20 A GMT-05

NYC SharePoint Developer Needed

Mon 12 May 08 12:09 P GMT-05

My Macbook Air is masculine, dammit!

Mon 17 Mar 08 6:59 P GMT-05
tags:          

iPhone Underrated as a Gaming Device?

Fri 14 Mar 08 1:50 P GMT-05
tags:        

My take on the iPhone SDK

Sat 08 Mar 08 1:39 P GMT-05

Jobs says "not likely" to Flash on the iPhone

Thu 06 Mar 08 1:39 A GMT-05
tags:          

My Macbook Air Review

Sun 02 Mar 08 4:20 P GMT-05

iPhone Roadmap March 6th

Fri 29 Feb 08 10:41 P GMT-05
tags:        

Video of the Macbook Air in Action

Wed 20 Feb 08 3:04 P GMT-05

Macbook Airはきれいですよ!

Sun 17 Feb 08 2:38 A GMT-05

Why is O'Reilly Condoning iPhone Hacking?

Mon 11 Feb 08 3:55 P GMT-05

Evaluating my next laptop purchase

Wed 06 Feb 08 8:40 P GMT-05

The iPhone SDK key has been leaked! Oh Noez!!!1

Tue 29 Jan 08 11:36 A GMT-05
tags:        

Why Geeks just don't "get" the Macbook Air

Thu 17 Jan 08 2:30 P GMT-05

Popcorn + TiVo + Macbook Pro + iPhone == Hell Yeah!

Tue 15 Jan 08 3:11 P GMT-05
tags:          

How my ADC membership changed my life

Mon 31 Dec 07 3:57 P GMT-05
tags:      

Leopard Code Sample : Sprinkling in some Bonjour

Tue 27 Nov 07 2:32 P GMT-05
tags:        

Leopard Sample: A Bound NSCollectionView

Mon 29 Oct 07 1:41 A GMT-05

Leopard is out - let the code samples begin!

Fri 26 Oct 07 10:09 A GMT-05
tags:          

My life is complete : iPhone SDK is CONFIRMED.

Wed 17 Oct 07 6:38 P GMT-05
tags:          

Leopard Shipping October 26th!!

Tue 16 Oct 07 4:59 P GMT-05
tags:        

My iPhone Review

Mon 23 Jul 07 1:09 P GMT-05
tags:        

Microsoft Codename Acropolis - Unwrapped

Wed 20 Jun 07 3:22 P GMT-05
tags:              

The dreaded language bleed-over has begun

Tue 19 Jun 07 6:23 P GMT-05
tags:        

Exploring the Delegate Design Pattern

Mon 14 May 07 6:30 P GMT-05

Core Data - Almost too Easy?

Wed 18 Apr 07 2:23 P GMT-05