I would think that the following code would not throw an exception if the value is null but is is. Am I missing a typo or is there a different way to do this?
if (![itemid isKindOfClass:[NSNull class]])
{
[record setValue:itemid forKey:#"itemid"];
}
Throws exception 'itemid NSNumber * (null) 0x14e8ebc0'
If itemid is nil (as opposed to an instance of the NSNull class), then -isKindOfClass: will return NO, and it will pass the condition and will try to set the value.
So, you probably want if (itemid && ![itemid isKindOfClass:[NSNull class]]) { ....
A message to a nil reference returns nil, or 0 or false in a numeric / bool context, regardless of the arguments to that message.
I'd like to check for an empty object (i.e. an object of an array which doesn't have a value) within an array which gets its data from a file.
As an example, if my array contains 12 objects (all NSString) and the object at index 11 doesn't return a value when its description is printed into the debug section of Xcode. I want to check if that is the case and respond accordingly. I already tried
if (!([MY_ARRAY objectAtIndex:11] == nil))
{
//Some Stuff
}
else
{
//Some other Stuff
}
which didn't work.
Any help is appreciated.
The description method is for debugging. You should not use it in your program logic. What are these objects, and what do they contain? Can you modify the objects to add an "isEmpty" property?
If you use NSNull, you'd use code like this:
NSArray *array = #{#"String", #(4), [NSNull null], #"Another string");
for (id anObject in array)
{
if (anObject =! [NSNull null]))
{
//Some Stuff
}
else
{
//Some other Stuff
}
}
You can check the length of the string: [string length] > 0
an object is an array cannot be nil, but you can use [NSNull null] which is an "object equivalent" to nil
As Jerome Diaz states, objects in an array can't be nil. The only option you have is to check the count property of the array if it reflects an expected value, or you can inspect the type/class of the object in the array. A safe way to include empty object into array is [NSNull null], but this is the task for the method that fills the array, not the one that reads it.
You can check the class type of an object in array with isKindOfClass or isMemberOfClass.
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
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
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;}