[__NSCFBoolean count]: unrecognized selector : Best way to prevent this crash - ios

I am getting this error on the conditional if statement. Is there a good way to prevent this error from showing up? Any tips or suggestions are appreciated. I am guessing subanswer for some reason is a boolean.
id subAnswer = [answer objectForKey:#"answer"];
NSArray *subAnswerKeyList;
if (subAnswer != [NSNull null] && subAnswer != nil && [subAnswer count] > 0 ) {
...
}

Replace your if statement with:
if ([subAnswer isKindOfClass:[NSArray class]] && [subAnswer count]) {
}
Your subAnswer is actually a number representing a BOOL value. You need to see why you expect it to be an array.

your "subAnswer" object is almost certainly not the NSArray object you're expecting it to be.
Put a "NSLog("subAnswer is %#", subAnswer);" in your code there and your Xcode console will tell you what the object really is.

Related

ios/objective-c: How can I prevent exception when inserting Null into core data?

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.

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.
}

ios check if array has object

From an array, I want to make a new mutable array holding all the items that meet a certain criteria. That's not the problem. The problem is checking if the array is empty.
if (!theDates]) {/*do something*/}
it comes back positive regardless, because the mutable array was created. But
if (![theDates objectAtIndex:0])
{
/* nothing got added to the array, so account for that */
}
else
{
/* do something with the array */
}
It crashes.
This crashes because although you have allocated your array, it's still empty. The line [theDates objectAtIndex:0] is trying to access the first object of an array, and due your array has none yet, it will crash.
To check the integrity of your array, just do this:
if (theDates.count > 0)
{
//Do something
id object = theDates[0]; //this for sure won't crash
}
Use [theDates count] > 0. You're accessing a possibly non-existent element, so it will crash when it's empty.
Or you could use the lastObject method which will return nil if the array is empty
if (![theDates lastObject]) { do something }
if( (theDates!=nil) && (theDates.count > 0))
{
//We have and existing array and something in there..
}
if (theDates != nil){
if (theDates.count > 0){
'do something'
}
}
This should check null array then check empty array which prevents nullpointerexception arises
This will work fine..
if (!URarray || !URarray.count){
// write code here
}

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

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