How do you test if an NSString is empty? or all whitespace or nil? with a single method call?
You can check if [string length] == 0 . This will check if it's a valid but empty string (@"") as well as if it's nil, since calling length on nil will also return 0. There are some very rare NSStrings where this will result in a false negative (saying the string isn't empty, when, for practical purposes, it is).
A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.
If you create an object using a method that begins with init, new, copy, or mutableCopy, then you own that object and are responsible for releasing it (or autoreleasing it) when you're done with it. If you create an object using any other method, that object is autoreleased, and you don't need to release it.
You can try something like this:
@implementation NSString (JRAdditions) + (BOOL)isStringEmpty:(NSString *)string { if([string length] == 0) { //string is empty or nil return YES; } if(![[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]) { //string is all whitespace return YES; } return NO; } @end
Check out the NSString
reference on ADC.
This is what I use, an Extension to NSString:
+ (BOOL)isEmptyString:(NSString *)string; // Returns YES if the string is nil or equal to @"" { // Note that [string length] == 0 can be false when [string isEqualToString:@""] is true, because these are Unicode strings. if (((NSNull *) string == [NSNull null]) || (string == nil) ) { return YES; } string = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; if ([string isEqualToString:@""]) { return YES; } return NO; }
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