yllan

Nowhere differentiable curve

2 notes

NSCollectionAddition

I know everyone has his own version of this because Objective-C somehow is a bit verbose. So here is my version.

If you haven’t start using similar extension, you may consider use this.

It let you:

  • ARRAY(a, b, c) instead of [NSArray arrayWithObjects: a, b, c, nil]
  • DICT(k1, v1, k2, v2) instead of [NSDictionary dictionaryWithObjects: v1, k1, v2, k2, nil]
  • SET(x, y, z) instead of [NSSet setWithObjects: x, y, z, nil]

(Thanks for Mike Ash, I steal these macros from his MACollectionUtilities.)

What if you want to upload jpeg files from a bunch of paths to flickr, five at a time? You can do this:

[[paths filter:^(NSString *path) { return [[path lowercaseString] hasSuffix: @".jpg"]; }]
    grouped: 5 block: ^(NSArray *jpegs) { [flickr uploadPhotos: jpegs]; }];

instead of

NSArray *jpegs = [paths filteredArrayUsingPredicate: [NSPredicate predicateWithBlock: ^(NSString *path, NSDictionary *bindings) { return [[path lowercaseString] hasSuffix: @".jpg"]; }]];
while ([jpegs count] > 0) {
    NSArray *group = [jpegs subarrayWithRange: NSMakeRange(0, MIN(5, [jpegs count]))];
    [flickr uploadPhotos: group];
    jpegs = [jpegs subarrauWithRange: NSMakeRange([group count], [jpegs count] - [group count])];
}

Both sucks, I know. But the problem of the plain-Cocoa version is, you can do too many things in a loop. It’s a too general program structure. You have to look down to figure out the intention of that loop. (Wether it is searching or filtering or grouping…)

With the help of methods like filter, grouped or foreach, the intention of code is more clear. That is, more understandable and concise code. (Well, I know nested bracket sucks.)

Comments and patches are welcome.

  1. zonble reblogged this from yllan
  2. yllan posted this