Created
March 10, 2012 07:22
-
-
Save tonyarnold/2010649 to your computer and use it in GitHub Desktop.
Exhaustively check if an Objective-C object is "empty"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static inline BOOL CBIsEmpty(id obj) { | |
return obj == nil | |
|| (NSNull *)obj == [NSNull null] | |
|| ([obj respondsToSelector:@selector(length)] && [obj length] == 0) | |
|| ([obj respondsToSelector:@selector(count)] && [obj count] == 0); | |
} |
I like that a lot. There are a lot of specific scenarios I'd handle differently than with the big block of ||
and &&
I have now. I'm using LLVM for everything now as well, so this will work. Thanks, Oliver!
I also added a fall through to your list, @orj (just to catch the unknown returns like dict values, etc) — most of the time I'm really just checking for nil:
BOOL __attribute__((overloadable)) CBIsEmpty(id object) { return object == nil; }
For completeness, how about:
BOOL __attribute__((overloadable)) CBIsEmpty(NSNull *n) { return YES; }
Out of interest @orj, why check for nil first? Wouldn't objc_msgSend do that for you, and faster?
Also why compare to "0u", is that for performance?
Cheers
Yeah, true. msgSend will indeed return 0 if the input is nil. And the 0u is just me being ultra pedantic. It is completely unnecessary.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You may wish to try something like this instead for extra type safety/speed. Only works with LLVM/Clang (see http://clang.llvm.org/docs/LanguageExtensions.html#overloading-in-c)