[ios] How do I test if a string is empty in Objective-C?

How do I test if an NSString is empty in Objective-C?

This question is related to ios objective-c nsstring

The answer is


You can have an empty string in two ways:

1) @"" // Does not contain space

2) @" " // Contain Space

Technically both the strings are empty. We can write both the things just by using ONE Condition

if ([firstNameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""].length==0)
{
    NSLog(@"Empty String");
}
else
{
    NSLog(@"String contains some value");
}

I put this:

@implementation NSObject (AdditionalMethod)
-(BOOL) isNotEmpty
{
    return !(self == nil
    || [self isKindOfClass:[NSNull class]]
    || ([self respondsToSelector:@selector(length)]
        && [(NSData *)self length] == 0)
    || ([self respondsToSelector:@selector(count)]
        && [(NSArray *)self count] == 0));

};
@end

The problem is that if self is nil, this function is never called. It'll return false, which is desired.


if( [txtMobile.text length] == 0 )
{
    [Utility showAlertWithTitleAndMessage: AMLocalizedString(@"Invalid Mobile No",nil) message: AMLocalizedString(@"Enter valid Mobile Number",nil)];
}

if(str.length == 0 || [str isKindOfClass: [NSNull class]]){
    NSLog(@"String is empty");
}
else{
    NSLog(@"String is not empty");
}    

Marc's answer is correct. But I'll take this opportunity to include a pointer to Wil Shipley's generalized isEmpty, which he shared on his blog:

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

Just use one of the if else conditions as shown below:

Method 1:

if ([yourString isEqualToString:@""]) {
        // yourString is empty.
    } else {
        // yourString has some text on it.
    }

Method 2:

if ([yourString length] == 0) {
    // Empty yourString
} else {
    // yourString is not empty
}

Just pass your string to following method:

+(BOOL)isEmpty:(NSString *)str
{
    if(str.length==0 || [str isKindOfClass:[NSNull class]] || [str isEqualToString:@""]||[str  isEqualToString:NULL]||[str isEqualToString:@"(null)"]||str==nil || [str isEqualToString:@"<null>"]){
        return YES;
    }
    return NO;
}

May be this answer is the duplicate of already given answers, but i did few modification and changes in the order of checking the conditions. Please refer the below code:

+(BOOL)isStringEmpty:(NSString *)str
    {
        if(str == nil || [str isKindOfClass:[NSNull class]] || str.length==0) {
            return YES;
       }
        return NO;
    }

The best way is to use the category.
You can check the following function. Which has all the conditions to check.

-(BOOL)isNullString:(NSString *)aStr{
        if([(NSNull *)aStr isKindOfClass:[NSNull class]]){
            return YES;
        }
        if ((NSNull *)aStr  == [NSNull null]) {
            return YES;
        }
        if ([aStr isKindOfClass:[NSNull class]]){
            return YES;
        }
        if(![[aStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]){
            return YES;
        }
        return NO;
    }

Simply Check your string length

 if (!yourString.length)
 {
   //your code  
 }

a message to NIL will return nil or 0, so no need to test for nil :).

Happy coding ...


if (string.length == 0) stringIsEmpty;

You can easily check if string is empty with this:

if ([yourstring isEqualToString:@""]) {
    // execute your action here if string is empty
}

One of the best solution I ever seen (better than Matt G's one) is this improved inline function I picked up on some Git Hub repo (Wil Shipley's one, but I can't find the link) :

// Check if the "thing" passed is empty
static inline BOOL isEmpty(id thing) {
    return thing == nil
    || [thing isKindOfClass:[NSNull class]]
    || ([thing respondsToSelector:@selector(length)]
        && [(NSData *)thing length] == 0)
    || ([thing respondsToSelector:@selector(count)]
        && [(NSArray *)thing count] == 0);
}

The best way in any case is to check the length of the given string.For this if your string is myString then the code is:

    int len = [myString length];
    if(len == 0){
       NSLog(@"String is empty");
    }
    else{
      NSLog(@"String is : %@", myString);
    }

- (BOOL)isEmpty:(NSString *)string{
    if ((NSNull *) string == [NSNull null]) {
        return YES;
    }
    if (string == nil) {
        return YES;
    }
    if ([string length] == 0) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) {
        return YES;
    }
    if([[string stringByStrippingWhitespace] isEqualToString:@""]){
        return YES;
    }
    return NO;
}

You should better use this category:

@implementation NSString (Empty)

    - (BOOL) isWhitespace{
        return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0);
    }

@end

Swift Version

Even though this is an Objective C question, I needed to use NSString in Swift so I will also include an answer here.

let myNSString: NSString = ""

if myNSString.length == 0 {
    print("String is empty.")
}

Or if NSString is an Optional:

var myOptionalNSString: NSString? = nil

if myOptionalNSString == nil || myOptionalNSString!.length == 0 {
    print("String is empty.")
}

// or alternatively...
if let myString = myOptionalNSString {
    if myString.length != 0 {
        print("String is not empty.")
    }
}

The normal Swift String version is

let myString: String = ""

if myString.isEmpty {
    print("String is empty.")
}

See also: Check empty string in Swift?


I have checked an empty string using below code :

//Check if we have any search terms in the search dictionary.
if( (strMyString.text==(id) [NSNull null] || [strMyString.text length]==0 
       || strMyString.text isEqual:@"")) {

   [AlertView showAlert:@"Please enter a valid string"];  
}

Very useful post, to add NSDictionary support as well one small change

static inline BOOL isEmpty(id thing) {
    return thing == nil
    || [thing isKindOfClass:[NSNull class]]
    || ([thing respondsToSelector:@selector(length)]
        && ![thing respondsToSelector:@selector(count)]
        && [(NSData *)thing length] == 0)
    || ([thing respondsToSelector:@selector(count)]
        && [thing count] == 0);
}

It is working as charm for me

If the NSString is s

if ([s isKindOfClass:[NSNull class]] || s == nil || [s isEqualToString:@""]) {

    NSLog(@"s is empty");

} else {

    NSLog(@"s containing %@", s);

}

So aside from the basic concept of checking for a string length less than 1, it is important to consider context deeply. Languages human or computer or otherwise might have different definitions of empty strings and within those same languages, additional context may further change the meaning.

Let's say empty string means "a string which does not contain any characters significant in the current context".

This could mean visually, as in color and background color are same in an attributed string. Effectively empty.

This could mean empty of meaningful characters. All dots or all dashes or all underscores might be considered empty. Further, empty of meaningful significant characters could mean a string that has no characters the reader understands. They could be characters in a language or characterSet defined as meaningless to the reader. We could define it a little differently to say the string forms no known words in a given language.

We could say empty is a function of the percentage of negative space in the glyphs rendered.

Even a sequence of non printable characters with no general visual representation is not truly empty. Control characters come to mind. Especially the low ASCII range (I'm surprised nobody mentioned those as they hose lots of systems and are not whitespace as they normally have no glyphs and no visual metrics). Yet the string length is not zero.

Conclusion. Length alone is not the only measure here. Contextual set membership is also pretty important.

Character Set membership is a very important common additional measure. Meaningful sequences are also a fairly common one. ( think SETI or crypto or captchas ) Additional more abstract context sets also exist.

So think carefully before assuming a string is only empty based on length or whitespace.


You can check either your string is empty or not my using this method:

+(BOOL) isEmptyString : (NSString *)string
{
    if([string length] == 0 || [string isKindOfClass:[NSNull class]] || 
       [string isEqualToString:@""]||[string  isEqualToString:NULL]  ||
       string == nil)
     {
        return YES;         //IF String Is An Empty String
     }
    return NO;
}

Best practice is to make a shared class say UtilityClass and ad this method so that you would be able to use this method by just calling it through out your application.


Its as simple as if([myString isEqual:@""]) or if([myString isEqualToString:@""])


You have 2 methods to check whether the string is empty or not:

Let's suppose your string name is NSString *strIsEmpty.

Method 1:

if(strIsEmpty.length==0)
{
    //String is empty
}

else
{
    //String is not empty
}

Method 2:

if([strIsEmpty isEqualToString:@""])
{
    //String is empty
}

else
{
    //String is not empty
}

Choose any of the above method and get to know whether string is empty or not.


Another option is to check if it is equal to @"" with isEqualToString: like so:

if ([myString isEqualToString:@""]) {
    NSLog(@"myString IS empty!");
} else {
    NSLog(@"myString IS NOT empty, it is: %@", myString);
}

Try the following

NSString *stringToCheck = @"";

if ([stringToCheck isEqualToString:@""])
{
   NSLog(@"String Empty");
}
else
{
   NSLog(@"String Not Empty");
}

check this :

if ([yourString isEqualToString:@""])
{
    NsLog(@"Blank String");
}

Or

if ([yourString length] == 0)
{
    NsLog(@"Blank String");
}

Hope this will help.


The first approach is valid, but doesn't work if your string has blank spaces (@" "). So you must clear this white spaces before testing it.

This code clear all the blank spaces on both sides of the string:

[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];

One good idea is create one macro, so you don't have to type this monster line:

#define allTrim( object ) [object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ]

Now you can use:

NSString *emptyString = @"   ";

if ( [allTrim( emptyString ) length] == 0 ) NSLog(@"Is empty!");

//Different validations:
 NSString * inputStr = @"Hey ";

//Check length
[inputStr length]

//Coming from server, check if its NSNull
[inputStr isEqual:[NSNull null]] ? nil : inputStr

//For validation in allowed character set
-(BOOL)validateString:(NSString*)inputStr
{
    BOOL isValid = NO;
    if(!([inputStr length]>0))
    {
        return isValid;

    }

    NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet characterSetWithCharactersInString:@".-"];
    [allowedSet formUnionWithCharacterSet:[NSCharacterSet decimalDigitCharacterSet]];
    if ([inputStr rangeOfCharacterFromSet:[allowedSet invertedSet]].location == NSNotFound)
    {
        // contains only decimal set and '-' and '.'

    }
    else
    {
        // invalid
        isValid = NO;

    }
    return isValid;
}

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to nsstring

NSRange to Range<String.Index> Creating NSData from NSString in Swift How do I check if a string contains another string in Swift? Converting NSString to NSDictionary / JSON convert NSDictionary to NSString How do I deserialize a JSON string into an NSDictionary? (For iOS 5+) How do I URL encode a string Objective-C and Swift URL encoding Convert an NSURL to an NSString Remove all whitespaces from NSString