Hacker News new | ask | show | jobs
by nomurrcy 5372 days ago
Or even (granted that I'm assuming the whole db api here is fake, and you'd actually probably be using core data here)

  NSArray *records = [[db find:[NSDictionary dictionaryWithObject:@"Joe" forKey:@"name"] limit:10]
                       sortedArrayUsingComparitor:^(id a, id b) {
                         // sort logic
                       }];
I typically add a category to NSArray for mapping a selector or block. The signatures are - (NSArray )mapBlock:(id (^)(id object))block; - (NSArray )mapSel:(SEL)selector;

Which would enable you to do it all in one statament:

  NSArray *records = [[[db find:[NSDictionary dictionaryWithObject:@"Joe" forKey:@"name"] 
                       limit:10]
                       sortedArrayUsingComparitor:^(id a, id b) {
                         // sort logic
                       }]
                       mapSel:@selector(lowercaseString)];
Also for mapping over an array you can usually use NSArrays valueForKey: which returns a new array which contains the result of calling valueForKey: on each member of the target array. As your sorting logic would typically exist in the db layer whether you were using CoreData or something else, it would be easy to write a wrapper such that you could write something like:

  [[[[MyFetchRequest forEntityNamed:@"foo"
          orderedBy:@"SomeKey"
          limit:10] fetch]
    valueForKey@"nameField.lowerCaseString"]
    enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
       // do stuff here
    }];
Again this is all 'fake' code as this is just a readability discussion.

I don't really agree with the article that nesting message-sends leads to unreadable code. I think reading obj-c is a lot like reading lisp s-expressions and your eye / brain quickly learns to read nested constructs. I generally try not to save anything to an explicit var that I don't intend to use somehow. (of course there are limits to this) I don't find nested code above difficult to read, YMMV.

1 comments

All 3 of your examples are viable; and you're right, Obj-C isn't that hard to read once you understand the syntax.