Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Interesting if you're already used to underscore.js.

The more Objective-C way to do this, without the dot syntax and the need for wrapping, is to add categories (sets of extra methods) to the NSArray and NSDictionary classes.

The square brackets don't impair chaining in any way - you can still [[[myDict allKeys] filter:filterMethod] invoke: invokeMethod]



I've tried that, but once you pass in blocks as arguments, the whole thing becomes a lot harder to read. I have no clue how to indent

    [[array filter:^BOOL (id obj) {
            return [obj passesTest];
        }]
        map:^id (id obj) {
            return [obj transformedObject]
        }];
Edit: Also, it's good practice to prefix your categories methods so they don't clash with other category's, so you'd have something like us_map:, us_filter:, reducing readability even further.


It should be a category on NSObject so it supports anything that supports fast enumeration which could be anything. And the indentation in the above is correct. The way you've implemented it is "anti-conventional" and bad form, imho.


Objective-C is a superset of C, functions can be just that - a function. Especially for higher-order functions like map and filter. Not everything needs to be glued to an object.


No shit sherlock.

That's not what he's doing, he's exposing blocks as properties because he couldn't wrap his head around indentation which is the wrong motivation. Maybe read the source before condescending next time.


Uh, I did read it. Yes, it's a bad idea. So is adding random things to NSObject for protocols that it does not conform to. That's actually worse, I'd argue, since you suddenly have -[UIColor map:]. What does that do? Pass RGBA NSNumbers to the block and return a new color? Throw an exception? Silently disregard the message and return nil? At least this approach has type checking.

Just declare a normal function, which can correctly throw a compiler warning if you try to pass anything that does not conform to NSFastEnumeration to it.


If indenting gets messy, just put the block in a separate variable. I think it's a shame Xcode doesn't give me an option to put accolades on the same vertical line (Xcode indenting prefers the K&R(?) style).


The blocks do make it messy but you don't need them, at least in this simple case, if you write your category to take selectors.

[[array filter:@selector(passesTest)] map:@selector(transformedObject)];

That's not perfect, but better.


as long as you don't need additional arguments :)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: