Clicky

iOS Dev Nugget 37 Checking if an Object is Empty

.

Need to run a code review on your codebase? Hire me

I'm sharing one of my most used function. It's just Wil Shipley's IsEmpty() renamed.

static inline BOOL moIsEmpty(id thing) {
    return thing == nil ||
        thing == [NSNull null] ||
        ([thing respondsToSelector:@selector(length)] && [(NSData*)thing length] == 0) ||
        ([thing respondsToSelector:@selector(count)]  && [(NSArray*)thing count] == 0);
}

Just put this into a header file and anytime you want to check if a container/string is empty — nil, [NSNull null], empty string, a container with no elements — you use moIsEmpty().

Also a convenience function wrapping it:

static inline BOOL moNotEmpty(id thing) {
    return !moIsEmpty(thing);
}


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues