Matt H. Matt H. - 9 months ago 42
Objective-C Question

NSString "nil or empty" check -- is this complete?

I was writing a small Category on NSString, and I wanted to know if this method is accurately handles all potential use cases:

Update: to clarify -- I wanted to make sure I'm not missing some oddball case involving character encodings, etc..

@implementation NSString (Helpers)

+(BOOL)stringIsNilOrEmpty:(NSString*)aString {
if (!aString)
return YES;
return [aString isEqualToString:@""];

Sample usage:

-(void) sampleUsage {
NSString *emptyString = @"";
NSString *nilString = nil;
NSAssert([NSString stringIsNilOrEmpty:nilString] == YES, @"String is nil/empty");
NSAssert([NSString stringIsNilOrEmpty:emptyString] == YES, @"String is nil/empty");


I only use the next conditional and do not even need a category:

if (!aString.length)

Using Objective-C theory, a message to NIL will return nil or zero, so basically you do not have to test for nil.