Underscore.js is described as a utility belt providing numerous helpers, and the capability of chaining commands for Javascript collections, functions, and more.
Robert Böhnke has created a library inspired by Underscore.js called Underscore.m with helpers for NSArray’s, NSDictionary’s, and other objects providing ways to easily execute a block on each item in a collection, helpers for comparison/shuffling, a way to chain these commands that is concise and readable and more.
Here’s the example given in the readme:
NSURL *twitterSearch = [NSURL URLWithString:@"http://search.twitter.com/search.json?q=@SoundCloud&rpp=100"];
// … then we fetch us some json …
NSData *data = [NSData dataWithContentsOfURL:twitterSearch];
// … and parse it.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:NULL];
// This is where the fun starts!
NSArray *tweets = [json valueForKey:@"results"];
NSArray *processed = _array(tweets)
// Let’s make sure that we only operate on NSDictionaries, you never
// know with these APIs 😉
.filter(Underscore.isDictionary)
// Remove all tweets that are in English
.reject(^BOOL (NSDictionary *tweet) {
return [[tweet valueForKey:@"iso_language_code"] isEqualToString:@"en"];
})
// Create a simple string representation for every tweet
.map(^NSString *(NSDictionary *tweet) {
NSString *name = [tweet valueForKey:@"from_user_name"];
NSString *text = [tweet valueForKey:@"text"];
return [NSString stringWithFormat:@"%@: %@", name, text];
})
.unwrap;
You can find Underscore.m on Github here.
You can find the homepage with extensive documentation and examples here.
I’d seen other “ports” of Underscore.m that seemed to have issues, but this one looks excellent.
Original article: Objective-C Utility Class Inspired By Underscore.js Providing Collection Helpers And More
©2012 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.