7

I have an NSString and I want to check if it has a NULL value. If it does, then the if condition should execute. Else it should execute the else condition.

Below is the code which I am using:

if ([appDelegate.categoryName isEqual:[NSNull null]])
{
    select = [[NSString alloc] initWithFormat:@"select * FROM ContentMaster LEFT JOIN Category ON ContentMaster.CategoryID=Category.CategoryID where ContentMaster.ContentTagText='%@'", appDelegate.tagInput];
}
else
{
    select = [[NSString alloc] initWithFormat:@"select * FROM ContentMaster LEFT JOIN Category ON ContentMaster.CategoryID=Category.CategoryID LEFT JOIN Topic ON ContentMaster.TopicID=Topic.TopicID where ContentMaster.ContentTagText='%@' && Category.CategoryName='%@' && Topic.TopicName='%@'", appDelegate.tagInput, appDelegate.categoryName, appDelegate.topicName];
}    

It always executes the else condition, and never the if condition, even when the value is NULL.

4
  • Show me your null value. Commented Oct 24, 2013 at 5:13
  • Since NSNull is a singleton, you could actually compare pointers directly: if (appDelegate.categoryName == [NSNull null]) Commented Oct 24, 2013 at 5:13
  • rather than comparing pointers use to check it is isKindOfClass[NSNull Class]. see my ans Commented Oct 24, 2013 at 5:22
  • possible duplicate of What is the right way to check for a null string in Objective-C? Commented Oct 24, 2013 at 5:23

10 Answers 10

36

In Objective-C and Cocoa, the property may not be set—that is, it's nil—or it may be set to the object representation of nil, which is an instance of NSNull. You probably want to check for either of these conditions, like this:

NSString* categoryName = appDelegate.categoryName;
if (categoryName == nil || categoryName == (id)[NSNull null]) {
  // nil branch
} else {
  // category name is set
}

This will execute the nil branch if the categoryName property is set to nil (the default for all properties), or if it's been explicitly set to the NSNull singleton.

Sign up to request clarification or add additional context in comments.

5 Comments

thanks it worked but can you please tell me one thing in else i have given querry it is fine but it does not return anything
SQL is select * FROM ContentMaster LEFT JOIN Category ON ContentMaster.CategoryID= Category.CategoryID LEFT JOIN Topic ON ContentMaster.TopicID=Topic.TopicID where ContentMaster.ContentTagText='Good' && Category.CategoryName='Product' && Topic.TopicName='M2M Operations'
this is the log of querry which is executing in else
@QueenSolutions What do you mean it doesn't return anything? The SQL query doesn't yield results, or are you saying that select is nil?
@QueenSolutions I suggest positing a new question and put more of the code in the loop in the new question. Ask why the value is not being set there, since this question is about a nil check.
3

The NULL value for Objective-C objects (type id) is nil.

While NULL is used for C pointers (type void *).

(In the end both end up holding the same value (0x0). They differ in type however.)

In Objective-C:

nil (all lower-case) is a null pointer to an Objective-C object.
Nil (capitalized) is a null pointer to an Objective-C class.
NULL (all caps) is a null pointer to anything else (C pointers, that is).
[NSNull null] (singleton) for situations where use of nil is not possible (adding/receiving nil to/from NSArrays e.g.)

So to check against NSNull one can either use:

if ((NSNull *)myString == [NSNull null])

or if one wants to omit the need of casting to NSNull:

if ([myString isKindOfClass:[NSNull class]])

Comments

0

Try to use this. Check your value is kind of NULL class or not rather than comparing Pointers value.

if ([appDelegate.categoryName isKindOfClass:[NSNull class]]){

        select = [[NSString alloc] initWithFormat:@"select * FROM ContentMaster LEFT JOIN  Category  ON  ContentMaster.CategoryID= Category.CategoryID where ContentMaster.ContentTagText='%@'",appDelegate.tagInput];

        }

    else {


      select = [[NSString alloc] initWithFormat:@"select * FROM ContentMaster LEFT JOIN  Category  ON  ContentMaster.CategoryID= Category.CategoryID  LEFT JOIN Topic ON ContentMaster.TopicID=Topic.TopicID where ContentMaster.ContentTagText='%@' && Category.CategoryName='%@' && Topic.TopicName='%@'",appDelegate.tagInput,appDelegate.categoryName,appDelegate.topicName];


    }

1 Comment

It's much more efficient and easier to read to just do a pointer comparison with the NSNull singleton. You also need to check if the property is simply not set (almost certainly the problem here). Avoid doing class comparisons, especially when the majority of the time they're going to fail—that is, this value is not going to be the NSNull singleton.
0
#define SAFESTRING(str) ISVALIDSTRING(str) ? str : @""
#define ISVALIDSTRING(str) (str != nil && [str isKindOfClass:[NSNull class]] == NO)
#define VALIDSTRING_PREDICATE [NSPredicate predicateWithBlock:^(id evaluatedObject, NSDictionary *bindings) {return (BOOL)ISVALIDSTRING(evaluatedObject);}]

SAFESTRING("PASS_OBJECT_HERE");

Comments

0

Its better to be on safer side in checking null values , as it can lead to crash.

if (![string isKindOfClass:[NSNull class]] && string && string != NULL) 

Comments

0

Use the following code:

-(void)viewDidLoad {
  [super viewDidLoad];
  //Example - 1
    NSString *myString;
    if([[self checkForNull:myString] isEqualToString:@""]){

        NSLog(@"myString is Null or Nil");

   }
   else{

     NSLog(@"myString contains %@",myString);

   }

 //Example - 2
   NSString *sampleString = @"iOS Programming";
    if([[self checkForNull:sampleString] isEqualToString:@""]){

        NSLog(@"sampleString is Null or Nil");

   }
   else{

     NSLog(@"sampleString contains %@",sampleString);

   }


}

-(id)checkForNull:(id)value{
    if ([value isEqual:[NSNull null]]) {

            return @"";
   }

    else if (value == nil)

            return @"";
    return value;

}

In Example -1, myString contains nothing. So the output is:

         myString is Null or Nil

In Example -2, sampleString contains some value. So the output is:

    sampleString contains iOS Programming

Comments

0
+(BOOL)isEmpty:(NSString *)str{
    if (str == nil || str == (id)[NSNull null] || [[NSString stringWithFormat:@"%@",str] length] == 0 || [[[NSString stringWithFormat:@"%@",str] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0){
        return YES;
    }
    return NO;
}

Just pass your string in Method :)

Comments

0

You can do it by using - [NSNull class]

if ([appDelegate.categoryName isEqual:[NSNull class]])
    {
        select = [[NSString alloc] initWithFormat:@"select * FROM ContentMaster LEFT JOIN Category ON ContentMaster.CategoryID=Category.CategoryID where ContentMaster.ContentTagText='%@'", appDelegate.tagInput];
    }
    else
    {
        select = [[NSString alloc] initWithFormat:@"select * FROM ContentMaster LEFT JOIN Category ON ContentMaster.CategoryID=Category.CategoryID LEFT JOIN Topic ON ContentMaster.TopicID=Topic.TopicID where ContentMaster.ContentTagText='%@' && Category.CategoryName='%@' && Topic.TopicName='%@'", appDelegate.tagInput, appDelegate.categoryName, appDelegate.topicName];
    }    

Comments

-2

Add an additional check for length also. This will definitely work.

if ([appDelegate.categoryName isEqual:[NSNull null]] && appDelegate.categoryName.length>0){


        select = [[NSString alloc] initWithFormat:@"select * FROM ContentMaster LEFT JOIN  Category  ON  ContentMaster.CategoryID= Category.CategoryID where ContentMaster.ContentTagText='%@'",appDelegate.tagInput];

        }        else {
          select = [[NSString alloc] initWithFormat:@"select * FROM ContentMaster LEFT JOIN  Category  ON  ContentMaster.CategoryID= Category.CategoryID  LEFT JOIN Topic ON ContentMaster.TopicID=Topic.TopicID where ContentMaster.ContentTagText='%@' && Category.CategoryName='%@' && Topic.TopicName='%@'",appDelegate.tagInput,appDelegate.categoryName,appDelegate.topicName];

    }

2 Comments

[appDelegate.categoryName isEqual:[NSNull null]] && appDelegate.categoryName.length > 0 you may want to freshen up on boolean arithmetic.
Yeah, that statement as written will cause the app to crash, since by definition if categoryName is the NSNull singleton, it doesn't respond to a length message.
-2
  NSString *str;

  if ([[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]          isEqualToString:@""] || str==nil) 
  {

  }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.