iObjectiveSee

Cocoa and iOS Development

building (array methods using) blocks

leave a comment

My friend Miguel and I recently learned about a few common Array methods in ruby which are invoked using blocks. Among the many appealing are some choice methods: #uniq, #each, #collect, #flatten, and #reject. We decided to implement a few of these in objective-c.

Say your original code resembles this:


NSArray *cities = [NSArray arrayWithObjects:@"New York", @"San Francisco", @"Seatle", @"Paris", @"Verbier", @"Jay Peak", nil];

NSString *favorite = @"Verbier";

 


- (BOOL)isAwesome {

BOOL isAws = NO;

for (NSString *str in cities) {

if ([str isEqualToString:favorite]) {

isAws = YES;

}

}

return isAws;

}

You can make it a lot more readable by writing something like this instead:


- (BOOL)isAwesome {

id favCity = [cities detect:^BOOL(NSString *str) {

return [str isEqualToString:favorite];

}];

return favCity ? YES:NO;

}

 

Grab the full implementation from github


- (void)each:(void (^)(id))block;

- (id)detect:(BOOL (^)(id))block;

- (NSArray *)collect:(id (^)(id obj))block;

- (NSArray *)reject:(BOOL (^)(id obj))block;

 

Written by Sarah

March 27th, 2012 at 12:56 am

Posted in Uncategorized

Leave a Reply