Skip to content

Instantly share code, notes, and snippets.

@brentsimmons
Created July 28, 2012 19:06
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brentsimmons/3194441 to your computer and use it in GitHub Desktop.
Save brentsimmons/3194441 to your computer and use it in GitHub Desktop.
Checking if an object is empty
BOOL RSIsEmpty(id obj) {
return obj == nil || obj == [NSNull null] || ([obj respondsToSelector:@selector(length)] && [(NSData *)obj length] == 0) || ([obj respondsToSelector:@selector(count)] && [obj count] == 0);
}
BOOL RSStringIsEmpty(NSString *s) {
/*22 Feb. 2011: added NSNull check. JSON parser can put a null where we expect a string, and NSNull throws an exception when checking length. Since [NSNull null] is, arguably, emptiness, it makes sense to include it.*/
return s == nil || (id)s == (id)[NSNull null] || [s length] == 0;
}
@brentsimmons
Copy link
Author

You've got three methods there instead of one function (and one optional function). And you'd need more to cover NSDictionary, NSSet, etc.

I'd also add: I have a bias against creating category methods. I create them sometimes, sure, I don't want to create my own personal dialect of Cocoa. I find it more lightweight to just have a couple functions.

@fjolnir
Copy link

fjolnir commented Jul 30, 2012

We just seem to have opposite biases.
Rather than having a function that tests for every possibility I like the approach of having multiple message responses, each performing only the exact amount of work required. I'm not however, saying that one or the other is invalid.

@brentsimmons
Copy link
Author

In general I agree with you completely -- the object-oriented approach is best. But I will consider that there are occasional special cases, and I think this is one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment