Underscore.m 是一个小型的工具库,用于方便在 Objective-C 中处理常见的数据结构。
它通过弃用方括号 [ ]] 来鼓励链式调用。
它受到了出色的 underscore.js 的启发。
// First, let's compose a twitter search request
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;
Underscore.m 的文档可以在 网站上找到。