I've recently started using Ick's 'andand' for Ruby so I can iterate through nested collections more easily than before.
Is there a version of this idiom for Objective-C implemented anywhere?
andand at rubygems
I'm not a Ruby programmer, so I may be missing something subtle, but it appears that andand makes it so that you can safely chain method calls even when one method call may return nil. This is built in in Objective-C, because calling methods on (actually properly termed sending messages to) nil is safe and perfectly acceptable. Messages to nil always return nil, and are basically a no-op. In Objective-C this is fine:
id foo = [someObject objectByDoingSomething]; // foo might be nil
id bar = [foo objectByDoingSomethingElse];
// If foo is nil, calling objectByDoingSomethingElse is essentially
// a no-op and returns nil, so bar will be nil
NSLog(@"foo: %@ bar: %@", foo, bar);
Therefore, this is fine too, even if objectByDoingSomething might return nil:
id foo = [[someObject objectByDoingSomething] objectByDoingSomethingElse];
From The Objective-C Programming Language: "In Objective-C, it is valid to send a message to nil—it simply has no effect at runtime." That document contains more detail about the exact behavior of calling methods on nil in Objective-C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With