Queen Solutions Queen Solutions - 4 months ago 11
iOS Question

How to check the NULL value in NSString in iOS?

I have NSSting i want to check if it has NULL value then if should work else it should execute the else condition.

here is my code which i am using to show.

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];


}


In this it always runs else not if even when value is NULL.

Answer

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.