how to Check NSString is null or not [duplicate] - ios

This question already has answers here:
How to detect if NSString is null?
(5 answers)
Closed 9 years ago.
I want to check weather a NSString is null or not. Im assigning from an JSON array. After assigning that string value is <null>. Now I want to check this string is null or not. So I put like this
if (myStringAuthID==nil) but this if statement always false. How I can check a string for null. Please help me
Thanks

Like that:
[myString isEqual: [NSNull null]];

There are three possible interpretations of "null" NSString:
someStringPtr == nil
(id)someStringPtr == [NSNull null]
someStringPtr.length == 0
If you may have the possibility of all 3, the 3rd check subsumes the first, but I don't know of a simple check for all three.
In general, JSON will return [NSNull null] for a null JSON value, but some kits may return #"" (length == 0) instead. nil will never be used in iOS since it can't be placed in arrays/dictionaries.

Try if(myString == [NSNull null]). That should evaluate it properly.

I think that is best if you check before cast it to an NSString or whatever, you have different options, the above are correct, but I prefer this:
id NilOrValue(id aValue) {
if ((NSNull *)aValue == [NSNull null]) {
return nil;
}
else {
return aValue;
}
}
Using this snippet (pay attention that is a C function) before passing the value to a pointer you can safely pass a value or nil if the value in NSNull. Passing nil is great, because if you send a message to a nil object, it doesn't throw an exception. You can also check for class type with -isKindOfClass.

Here is part of a string category I created:
#interface NSString (Enhancements)
+(BOOL)isNullOrEmpty:(NSString *)inString;
#end
#implementation NSString (Enhancements)
+(BOOL)isNullOrEmpty:(NSString *)inString
{
BOOL retVal = YES;
if( inString != nil )
{
if( [inString isKindOfClass:[NSString class]] )
{
retVal = inString.length == 0;
}
else
{
NSLog(#"isNullOrEmpty, value not a string");
}
}
return retVal;
}
#end

Related

How can I check if an object in an NSArray is NSNull?

I am getting an array with null value. Please check the structure of my array below:
(
"< null>"
)
When I'm trying to access index 0 its crashing because of
-[NSNull isEqualToString:]: unrecognized selector sent to instance 0x389cea70
Currently its crashing because of that array with a crash log:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull isEqualToString:]: unrecognized selector sent to instance 0x389cea70'
*** First throw call stack:
(0x2d9fdf53 0x3820a6af 0x2da018e7 0x2da001d3 0x2d94f598 0x1dee57 0x1dfd31 0x302f598d 0x301a03e3 0x3052aeed 0x3016728b 0x301659d3 0x3019ec41 0x3019e5e7 0x30173a25 0x30172221 0x2d9c918b 0x2d9c865b 0x2d9c6e4f 0x2d931ce7 0x2d931acb 0x3262c283 0x301d3a41 0xabb71 0xabaf8)
libc++abi.dylib: terminating with uncaught exception of type NSException
id object = myArray[0];// similar to [myArray objectAtIndex:0]
if(![object isEqual:[NSNull null]])
{
//do something if object is not equals to [NSNull null]
}
if (myArray != (id)[NSNull null])
OR
if(![myArray isKindOfClass:[NSNull class]])
Building off of Toni's answer I made a macro.
#define isNSNull(value) [value isKindOfClass:[NSNull class]]
Then to use it
if (isNSNull(dict[#"key"])) ...
Awww, guys. This is an easy one.
// if no null values have been returned.
if ([myValue class] == [NSNull class]) {
myValue = nil;
}
I'm sure there are better answers, but this one works.
I found the code for working with NSNull has the following problems:
Looks noisy and ugly.
Time consuming.
Error prone.
So I created the following category:
#interface NSObject (NSNullUnwrapping)
/**
* Unwraps NSNull to nil, if the object is NSNull, otherwise returns the object.
*/
- (id)zz_valueOrNil;
#end
With the implementation:
#implementation NSObject (NSNullUnwrapping)
- (id)zz_valueOrNil
{
return self;
}
#end
#implementation NSNull (NSNullUnwrapping)
- (id)zz_valueOrNil
{
return nil;
}
#end
It works by the following rules:
If a category is declared twice for the same Class (ie singleton instance of the Class type) then behavior is undefined. However, a method declared in a subclass is allowed to override a category method in its super-class.
This allows for more terse code:
[site setValue:[resultSet[#"main_contact"] zz_valueOrNil] forKey:#"mainContact"];
. . as opposed to having extra lines to check for NSNull. The zz_ prefix looks a little ugly but is there for safety to avoid namespace collisions.
You can use the following check:
if (myArray[0] != [NSNull null]) {
// Do your thing here
}
The reason for this can be found on Apple's official docs:
Using NSNull
The NSNull class defines a singleton object you use to represent null values in situations where nil is prohibited as a value (typically in a collection object such as an array or a dictionary).
NSNull *nullValue = [NSNull null];
NSArray *arrayWithNull = #[nullValue];
NSLog(#"arrayWithNull: %#", arrayWithNull);
// Output: "arrayWithNull: (<null>)"
It is important to appreciate that the NSNull instance is semantically different from NO or false—these both represent a logical value; the NSNull instance represents the absence of a value. The NSNull instance is semantically equivalent to nil, however it is also important to appreciate that it is not equal to nil. To test for a null object value, you must therefore make a direct object comparison.
id aValue = [arrayWithNull objectAtIndex:0];
if (aValue == nil) {
NSLog(#"equals nil");
}
else if (aValue == [NSNull null]) {
NSLog(#"equals NSNull instance");
if ([aValue isEqual:nil]) {
NSLog(#"isEqual:nil");
}
}
// Output: "equals NSNull instance"
Taken from https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/NumbersandValues/Articles/Null.html
A lot of good and interesting answers have been given already and (nealry) all of them work.
Just for completion (and the fun of it):
[NSNull null] is documented to return a singleton. Therefore
if (ob == [NSNull null]) {...}
works fine too.
However, as this is an exception I don't think that using == for comparing objects is a good idea in general. (If I'd review your code, I'd certainly comment on this).
In Swift (or bridging from Objective-C), it is possible to have NSNull and nil in an array of optionals. NSArrays can only contain objects and will never have nil, but may have NSNull. A Swift array of Any? types may contain nil, however.
let myArray: [Any?] = [nil, NSNull()] // [nil, {{NSObject}}], or [nil, <null>]
To check against NSNull, use is to check an object's type. This process is the same for Swift arrays and NSArray objects:
for obj in myArray {
if obj is NSNull {
// object is of type NSNull
} else {
// object is not of type NSNull
}
}
You can also use an if let or guard to check if your object can be casted to NSNull:
guard let _ = obj as? NSNull else {
// obj is not NSNull
continue;
}
or
if let _ = obj as? NSNull {
// obj is NSNull
}
Consider this approach:
Option 1:
NSString *str = array[0];
if ( str != (id)[NSNull null] && str.length > 0 {
// you have a valid string.
}
Option 2:
NSString *str = array[0];
str = str == (id)[NSNull null]? nil : str;
if (str.length > 0) {
// you have a valid string.
}

If I'm sorting objects using compare, how do I tell it to not sort if one of the objects is nil?

Say I have the following block of code:
[allKeys sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDictionary *firstArticle = [articles objectForKey:(NSString *)obj1];
NSNumber *firstSortID = [firstArticle objectForKey:#"sort_id"];
NSDictionary *secondArticle = [articles objectForKey:(NSString *)obj2];
NSNumber *secondSortID = [secondArticle objectForKey:#"sort_id"];
if (firstSortID == nil || secondSortID == nil) {
return nil;
}
else {
return [secondSortID compare:firstSortID];
}
}];
I get the warning:
Incompatible pointer to integer conversion returning 'void *' from a
function with result type 'NSComparisonResult' (aka 'enum
NSComparisonResult')
But basically, if one of them is nil, it crashes because the comparison doesn't make sense. How do I tell it that if it's nil, don't bother, just stop.
You have to decide how you want nil values to be sorted. Most likely they should go at the end of the list. You want something like this:
if (firstSortID) {
if (secondSortID) {
// Both set, compare
NSComparisonResult result = [firstSortID compare:secondSortID];
if (result == NSOrderedSame) {
// optionally do another comparison on a secondary value
// result = ...
}
return result;
} else {
// Have 1st but not 2nd
return NSOrderedAscending;
}
} else {
if (secondSortID) {
// Have 2nd but not 1st
return NSOrderedDescending;
} else {
// Both nil, treat as the same
// Another option here is to look at another value in the dictionary to be used as a secondary sort
return NSOrderedSame;
}
}
You cannot prematurely terminate the sort using sortUsingComparator:. So you must sort the nil values - just decide whether nil should be the least or greatest value and return NSOrderedDescending, NSOrderedAscending or NSOrderedSame as appropriate.
If you need to know whether you hit a nil then set a flag in your block which you can test afterwards. The flag needs to be declared with the __block qualifier so it can be modified within your block, e.g.:
__block BOOL nilFound = NO;
[allKeys sortUsingComparator:^NSComparisonResult(id obj1, id obj2)
{
NSDictionary *firstArticle = [articles objectForKey:(NSString *)obj1];
NSNumber *firstSortID = [firstArticle objectForKey:#"sort_id"];
NSDictionary *secondArticle = [articles objectForKey:(NSString *)obj2];
NSNumber *secondSortID = [secondArticle objectForKey:#"sort_id"];
// set flag - could alternatively be set during comparison logic below
if (firstSortID == nil || secondSortID == nil)
nilFound = YES;
// actual comparison, allowing for nil values
...
}];
// was a nil found?
if (nilFound) ...
Addendum
Others have raised the issue of a stable sort, you should be able to address this by using the original keys, e.g.:
if (firstSortID == nil)
{
if (secondSortID == nil)
{
// both nil - use original keys as secondary sort, obj1 & obj2 are strings
return [obj1 compare:obj2];
}
else
return NSSortAscending;
}
else
return secondSortID == nil ? NSSortDescending : [secondSortID compare:firstSortID];
(You can switch the NSSortAscending & NSSortDescending to have the nil values grouped at the other end.)

ios check if nsarray == null

I'm receiving some response from JSON, and is working fine, but I need to check for some null values,
I have found different answers but seems is not working still,
NSArray *productIdList = [packItemDictionary objectForKey:#"ProductIdList"];
I have tried with
if ( !productIdList.count ) //which breaks the app,
if ( productIdList == [NSNull null] ) // warning: comparison of distinct pointer types (NSArray and NSNull)
So what is happening? How to fix this and check for null in my array?
Thanks!
Eliminate the warning using a cast:
if (productIdList == (id)[NSNull null])
If productIdList is in fact [NSNull null], then doing productIdList.count will raise an exception because NSNull does not understand the count message.
You can also check class of an object by using method isKindOfClass:.
For example, in your case you could do following:
if ([productIdList isKindOfClass:[NSArray class]])
{
// value is valid
}
or (if you are sure that NSNull is indicating invalid value)
if([productIdList isKindOfClass:[NSNull class]])
{
// value is invalid
}
You can use the isEqual selector:
if ( [productIdList isEqual:[NSNull null]] )
you should be clear what you want to check:
the array is null which means the variable doesn't exist:
array == nil
Or the array has zero element which you can :
[array count] == 0

Want to compare string with null iOS sdk

I want to comapre my string with null values I am getting from my local database.
I tried if (exe_lbl_data.text==nil) and also if (exe_lbl_data.text=#"(null)") but both are showing false.
try one or both of the following:
if (nil == str || NSNull.null == (id)str) {
…
}
In this case, you need to define what Null is. There is a Null type (NS/CF-Null), and there is the concept of the Null pointer. It varies by case (that is, what is returned to you?).
try below statement :
[string length] == 0
or
[string isKindOfClass:[NSNull class]];

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

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?
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.
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.
Refer to the following related articles on this site:
Is if (variable) the same as if (variable != nil) in Objective-C
h
I think your error is related to something else as you shouldn't need to do the extra checking.
Also see this related question: Proper checking of nil sqlite text column
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.
Whats with all these "works for me answers" ? We're all coding in the same language and the rules are
Ensure the reference isn't nil
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.
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);
}
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.
You just check for nil
if(data[#"Bonds"]==nil){
NSLog(#"it is nil");
}
or
if ([data[#"Bonds"] isKindOfClass:[NSNull class]]) {
NSLog(#"it is null");
}
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!
}
if(textfield.text.length == 0){
//do your desired work
}
Try this for check null
if (text == nil)
#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.
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
What works for me is if ( !myobject )
Complete checking of a string for null conditions can be a s follows :<\br>
if(mystring)
{
if([mystring isEqualToString:#""])
{
mystring=#"some string";
}
}
else
{
//statements
}
I only check null string with
if ([myString isEqual:[NSNull null]])
if ([linkedStr isEqual:(id)[NSNull null]])
{
_linkedinLbl.text=#"No";
}else{
_linkedinLbl.text=#"Yes";
}
if ([strpass isEqual:[NSNull null]] || strpass==nil || [strpass isEqualToString:#"<null>"] || [strpass isEqualToString:#"(null)"] || strpass.length==0 || [strpass isEqualToString:#""])
{
//string is blank
}
For string:
+ (BOOL) checkStringIsNotEmpty:(NSString*)string {
if (string == nil || string.length == 0) return NO;
return YES;
}
Refer the picture below:
For string:
+ (BOOL) checkStringIsNotEmpty:(NSString*)string {
if (string == nil || string.length == 0) return NO;
return YES;}

Resources