Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString is empty

How do you test if an NSString is empty? or all whitespace or nil? with a single method call?

like image 503
Yazzmi Avatar asked Aug 08 '10 21:08

Yazzmi


People also ask

How do I know if NSString is empty?

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).

What is NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.

Do I need to release NSString?

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.


2 Answers

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.

like image 176
Jacob Relkin Avatar answered Oct 01 '22 06:10

Jacob Relkin


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;   } 
like image 34
scooter133 Avatar answered Oct 01 '22 05:10

scooter133