What is the right way to check for a null string in Objective-C?

IosObjective CCocoa Touch

Ios Problem Overview


I was using this in my iPhone app

if (title == nil) {
    // do something
}

but it throws some exception, and the console shows that the title is "(null)".

So I'm using this now:

if (title == nil || [title isKindOfClass:[NSNull class]]) {
    //do something
}

What is the difference, and what is the best way to determine whether a string is null?

Ios Solutions


Solution 1 - Ios

As others have pointed out, there are many kinds of "null" under Cocoa/Objective C. But one further thing to note is that [title isKindOfClass:[NSNull class]] is pointlessly complex since [NSNull null] is documented to be a singleton so you can just check for pointer equality. See Topics for Cocoa: Using Null.

So a good test might be:

if (title == (id)[NSNull null] || title.length == 0 ) title = @"Something";

Note how you can use the fact that even if title is nil, title.length will return 0/nil/false, ie 0 in this case, so you do not have to special case it. This is something that people who are new to Objective C have trouble getting used to, especially coming form other languages where messages/method calls to nil crash.

Solution 2 - Ios

it is just as simple as

if([object length] >0)
{
  // do something
}

remember that in objective C if object is null it returns 0 as the value.

This will get you both a null string and a 0 length string.

Solution 3 - Ios

Refer to the following related articles on this site:

I think your error is related to something else as you shouldn't need to do the extra checking.

Also see this related question: https://stackoverflow.com/questions/598396/proper-checking-of-nil-sqlite-text-column

Solution 4 - Ios

I have found that in order to really do it right you end up having to do something similar to

if ( ( ![myString isEqual:[NSNull null]] ) && ( [myString length] != 0 ) ) {
}

Otherwise you get weird situations where control will still bypass your check. I haven't come across one that makes it past the isEqual and length checks.

Solution 5 - Ios

Whats with all these "works for me answers" ? We're all coding in the same language and the rules are

  1. Ensure the reference isn't nil
  2. Check and make sure the length of the string isn't 0

That is what will work for all. If a given solution only "works for you", its only because your application flow won't allow for a scenario where the reference may be null or the string length to be 0. The proper way to do this is the method that will handle what you want in all cases.

Solution 6 - Ios

If you want to test against all nil/empty objects (like empty strings or empty arrays/sets) you can use the following:

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

Solution 7 - Ios

There are two situations:

It is possible that an object is [NSNull null], or it is impossible.
Your application usually shouldn't use [NSNull null]; you only use it if you want to put a "null" object into an array, or use it as a dictionary value. And then you should know which arrays or dictionaries might contain null values, and which might not.
If you think that an array never contains [NSNull null] values, then don't check for it. If there is an [NSNull null], you might get an exception but that is fine: Objective-C exceptions indicate programming errors. And you have a programming error that needs fixing by changing some code.

If an object could be [NSNull null], then you check for this quite simply by testing
(object == [NSNull null]). Calling isEqual or checking the class of the object is nonsense. There is only one [NSNull null] object, and the plain old C operator checks for it just fine in the most straightforward and most efficient way.

If you check an NSString object that cannot be [NSNull null] (because you know it cannot be [NSNull null] or because you just checked that it is different from [NSNull null], then you need to ask yourself how you want to treat an empty string, that is one with length 0. If you treat it is a null string like nil, then test (object.length == 0). object.length will return 0 if object == nil, so this test covers nil objects and strings with length 0. If you treat a string of length 0 different from a nil string, just check if object == nil.

Finally, if you want to add a string to an array or a dictionary, and the string could be nil, you have the choice of not adding it, replacing it with @"", or replacing it with [NSNull null]. Replacing it with @"" means you lose the ability to distinguish between "no string" and "string of length 0". Replacing it with [NSNull null] means you have to write code when you access the array or dictionary that checks for [NSNull null] objects.

Solution 8 - Ios

You just check for nil

if(data[@"Bonds"]==nil){
  NSLog(@"it is nil");
}

or

if ([data[@"Bonds"] isKindOfClass:[NSNull class]]) {
    NSLog(@"it is null");
}

Solution 9 - Ios

MACRO Solution (2020)

Here is the macro that I use for safe string instead of getting "(null)" string on a UILabel for example:

#define SafeString(STRING) ([STRING length] == 0 ? @"" : STRING)

let say you have an member class and name property, and name is nil:

NSLog(@"%@", member.name); // prints (null) on UILabel

with macro:

NSLog(@"%@", SafeString(member.name)); // prints empty string on UILabel

nice and clean 

Extension Solution (2020)

If you prefer checking nil Null and empty string in your project you can use my extension line below:

NSString+Extension.h

///
/// Checks if giving String is an empty string or a nil object or a Null.
/// @param string string value to check.
///
+ (BOOL)isNullOrEmpty:(NSString*)string;

NSString+Extension.m

+ (BOOL)isNullOrEmpty:(NSString*)string {
    if (string) { // is not Nil
        NSRange range = [string rangeOfString:string];
        BOOL isEmpty = (range.length <= 0 || [string isEqualToString:@" "]);
        BOOL isNull = string == (id)[NSNull null];
    
        return (isNull || isEmpty);
    }
    
    return YES;
}

###Example Usage

if (![NSString isNullOrEmpty:someTitle]) {
    // You can safely use on a Label or even add in an Array for example. Remember: Arrays don't like the nil values!
}

Solution 10 - Ios

if(textfield.text.length == 0){
   //do your desired work
}

Solution 11 - Ios

Try this for check null

 if (text == nil)

Solution 12 - Ios

@interface NSString (StringFunctions)
- (BOOL) hasCharacters;
@end

@implementation NSString (StringFunctions)
- (BOOL) hasCharacters {
    if(self == (id)[NSNull null]) {
        return NO;
    }else {
        if([self length] == 0) {
            return NO;
        }
    }
    return YES;
}
@end

NSString *strOne = nil;
if([strOne hasCharacters]) {
    NSLog(@"%@",strOne);
}else {
    NSLog(@"String is Empty");
}

This would work with the following cases, NSString *strOne = @"" OR NSString *strOne = @"StackOverflow" OR NSString *strOne = [NSNull null] OR NSString *strOne.

Solution 13 - Ios

If that kind of thing does not already exist, you can make an NSString category:

@interface NSString (TrucBiduleChoseAdditions)

- (BOOL)isEmpty;

@end

@implementation NSString (TrucBiduleChoseAdditions)

- (BOOL)isEmpty {
    return self == nil || [@"" isEqualToString:self];
}

@end

Solution 14 - Ios

What works for me is if ( !myobject )

Solution 15 - Ios

Complete checking of a string for null conditions can be a s follows :<\br>

if(mystring)
{
if([mystring isEqualToString:@""])
{
mystring=@"some string";
}
}
else { //statements }

Solution 16 - Ios

I only check null string with

> if ([myString isEqual:[NSNull null]])

Solution 17 - Ios

if ([linkedStr isEqual:(id)[NSNull null]])
                {
                    _linkedinLbl.text=@"No";
                }else{
                    _linkedinLbl.text=@"Yes";
                }
                

Solution 18 - Ios

if ([strpass isEqual:[NSNull null]] || strpass==nil || [strpass isEqualToString:@"<null>"] || [strpass isEqualToString:@"(null)"] || strpass.length==0 || [strpass isEqualToString:@""])
{
    //string is blank  
}

Solution 19 - Ios

For string:

+ (BOOL) checkStringIsNotEmpty:(NSString*)string {
if (string == nil || string.length == 0) return NO;
return YES;

}

Refer the picture below:

enter image description here

Solution 20 - Ios

For string:

+ (BOOL) checkStringIsNotEmpty:(NSString*)string {
if (string == nil || string.length == 0) return NO;
return YES;}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTeo Choong PingView Question on Stackoverflow
Solution 1 - IosPeter N LewisView Answer on Stackoverflow
Solution 2 - IosBluephlameView Answer on Stackoverflow
Solution 3 - IosTimMView Answer on Stackoverflow
Solution 4 - IosAfroRickView Answer on Stackoverflow
Solution 5 - IosnenchevView Answer on Stackoverflow
Solution 6 - IosdiederikhView Answer on Stackoverflow
Solution 7 - Iosgnasher729View Answer on Stackoverflow
Solution 8 - IosGami NileshView Answer on Stackoverflow
Solution 9 - IosmgykyView Answer on Stackoverflow
Solution 10 - IosMuhammad Aamir AliView Answer on Stackoverflow
Solution 11 - IosVineesh TPView Answer on Stackoverflow
Solution 12 - IosHemangView Answer on Stackoverflow
Solution 13 - IosRémyView Answer on Stackoverflow
Solution 14 - IosJoseph Bolade Caxton-IdowuView Answer on Stackoverflow
Solution 15 - IosAlen AlexanderView Answer on Stackoverflow
Solution 16 - IosJerryZhouView Answer on Stackoverflow
Solution 17 - IosSWAMY CHUNCHUView Answer on Stackoverflow
Solution 18 - Iossaurabh rathodView Answer on Stackoverflow
Solution 19 - IosAmyNguyenView Answer on Stackoverflow
Solution 20 - IosAmyNguyenView Answer on Stackoverflow