NSString contains : <null> and is crashing my app - iphone

I've an NSString thats populated from some data returned via JSON.
The code works great under normal circumstances but there is an occasion when i get returned by the JSON.
When i do a check to see if my NSString == nil or == null it fails the test.
But the fact that the NSString contains crashes my app.
So does have some special meaning in Objective C? Or should i just do a string compare and see if the string is equal to rather than being nil and handle it that way.
This has me a little confused.
Many Thanks,
Code

<null> is what NSNull returns for its -description method. You need to also check for
myString == [NSNull null]
in this case.
Additional info: IIRC the common Objective-C JSON stuff will use [NSNull null] for nulls in the JSON structure, to differentiate the value from one that simply isn't there.

NSString * is just a pointer to a NSString object.
To test for null pointer:
NSString *str;
if (str) {
// str points to an object
if ([str length] == 0) {
// string is empty
}
} else
// str points to nothing
}
If you want to check for whitespace, you can trim the NSString with stringByTrimmingCharactersInSet.

You could check to see if it's null by.
if ([str isKindOfClass:[NSNull class]]) {
// str is null.
}

I did it this way:
if([string isKindOfClass:[NSNull class]]) {
NSLog(#"This is JSON null");
} else {
NSLog(#"This is a string, do what you wanna do with it");
}

Related

How to check if value in array is not NULL?

So I am parsing a twitter timeline. There is a field called "following" in the JSON response. It should be true or false.
But sometimes the field is missing.
When I do:
NSLog(#"%#", [[[timeline objectAtIndex:i] objectForKey:#"user"] objectForKey:#"following"]);
This is the output:
1
1
0
0
1
<null>
1
1
So how to check for those values?
NSArray and other collections can't take nil as a value, since nil is the "sentinel value" for when the collection ends. You can find if an object is null by using:
if (myObject == [NSNull null]) {
// do something because the object is null
}
If the field is missing, NSDictionary -objectForKey: will return a nil pointer. You can test for a nil pointer like this:
NSNumber *following = [[[timeline objectAtIndex:i] objectForKey:#"user"] objectForKey:#"following"];
if (following)
{
NSLog(#"%#", following);
}
else
{
// handle no following field
NSLog(#"No following field");
}
It's not the timeline element that's null. It's either the "user" dictionary or the "following" object that's null. I recommend creating a user model class to encapsulate some of the json/dictionary messiness. In fact, I bet you could find an open source Twitter API for iOS.
Either way, your code would be more readable as something like:
TwitterResponse *response = [[TwitterResponse alloc] initWithDictionary:[timeline objectAtIndex:i]];
NSLog(#"%#", response.user.following);
TwitterResponse above would implement a readonly property TwitterUser *user which would in turn implement NSNumber *following. Using NSNumber because it would allow null values (empty strings in the JSON response).
Hope this helps get you on the right track. Good luck!
for checking array contain null value use this code.
if ([array objectAtIndex:0] == [NSNull null])
{
//do something
}
else
{
}

String isNullOrEmpty as a category

I'm trying to create a method which checks for a null/nil/empty string, and I'm trying to get it working as a category but having no luck.
I'm using this code, based on answers in this topic:
#implementation NSString (NSStringExtension)
- (BOOL)isNullOrEmpty {
return self == nil ||
self == (id)[NSNull null] ||
[#"" isEqualToString:self] ||
[[self stringByReplacingOccurrencesOfString:#" " withString:#""] length] == 0||
[self isEqualToString:#"(null)"]
|| ([self respondsToSelector:#selector(length)] && [(NSData *) self length] == 0)
|| ([self respondsToSelector:#selector(count)] && [(NSArray *) self count] == 0)
|| [[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0;
}
#end
Yet when I try to use this this is what I get:
NSLog([#"" isNullOrEmpty] ? #"1":#"0"); // prints 1
NSString *s1 = nil;
NSLog([s1 isNullOrEmpty] ? #"1":#"0"); // prints 0
NSLog([args.itemName isNullOrEmpty] ? #"1":#"0"); // prints 0
NSLog([(NSString*)nil isNullOrEmpty] ? #"1":#"0"); // prints 0
This is baffling me, and I can only assume that some combination of iOS5/ARC is causing the nil object to be coerced to a blank string/pointer. The debugger shows the string as 0x0, yet when I use my isNullOrEmpty method, I get false.
return self == nil
This can never happen. If you try to send isNullOrEmpty (or any other message) to nil, nothing happens (objc_msgSend(), the function responsible for message dispatch, checks for a nil reciever as one of the first things it does and aborts).
self == (id)[NSNull null]
This will also never happen. If you send isNullOrEmpty to an object that's an instance of NSNull, your method here, which is a method on NSString, will not be called. Instead, NSNull's version (which probably doesn't exist) will be.
Likewise, ([self respondsToSelector:#selector(count)] && [(NSArray *) self count]) is never going to happen. If the object is an NSArray, then isNullOrEmpty will never run, because, again, it's a method of NSString.
Correspondingly, [(NSData *) self length] doesn't do what you think it does. NSString instances do respond to length, but casting the object to NSData doesn't use the NSData version of the method -- it still ends up as the NSString version of length, because the object actually is an NSString (casting only happens at compile-time; it can't change anything at run-time).
[self isEqualToString:#"(null)"]
Here you appear to be checking for nil again, but you are being misled by the representation that NSLog chooses when it prints nil:
NSLog(#"%#", nil);
This displays (null) in the console, but that doesn't mean that the object itself is a string with those characters. NSLog just chooses that string to display for nil.*
Several of the things you are doing would require this to be in a category on NSObject, so that the method would in fact be called even if the object was not an NSString.
To check for a string consisting only of whitespace, all you need is the comparison to the empty string #"" after trimming whitespace:
NSString * trimmedSelf = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
// Then either:
[trimmedSelf isEqualToString:#""];
// Or:
([trimmedSelf length] == 0);
*And even better, doing NSLog(#"%#", [NSNull null]); displays <null> (angle brackets instead of parentheses), wonderfully confusing the first few times you encounter NSNull.
Another approach can be to define a simple macro.
#define NSStringIsNullOrEmpty(str) ((str==nil) || [(str) isEqualToString:#""])
It's simple and effective. If you do not like macros you can always convert it to a function call without affecting the rest of your code.
-- Update:
#Bryan has raised a good point. An inline function is a great way to go. Here is an updated macro that will evaluate str only once.
#define NSStringIsNullOrEmpty(str) ({ NSString *_str=(str); ((tmp==nil) || [tmp isEqualToString:#""]);})
In Objective-C, sending a message to nil will always return 0 (or NO, a zeroed-out struct, NULL, etc., depending on the declared return type). The isNullOrEmpty method that you wrote won't actually be invoked when you send isNullOrEmpty to nil. See the accepted answer to Sending a message to nil? for more information.
Perhaps you could change your method to be isNotNullOrEmpty. Then a return value of 0 when sending isNotNullOrEmpty to nil will make sense.
You aren't calling your method, but sending a message to nil.
This is expected behavior. You are sending a message to nil after all. So it is returning either nil (or some other 0 value). Which short circuits to false so that '0' is printed in the cases shown below:
NSLog([s1 isNullOrEmpty] ? #"1":#"0"); // prints 0
NSLog([(NSString*)nil isNullOrEmpty] ? #"1":#"0"); // prints 0
You can even confirm your message is not being called for those cases by setting a breakpoint in your new category method.
Like others have said, calling [nil isNullOrEmpty]; will not actually run your method. The nil object is just that : empty itself.
As a solution, I'd like to say that it's not because you're in an Object-Oriented language that you must never use functions.
BOOL IsStringNilOrEmpty(NSString*)str
{
return str == nil ||
str == null ||
[#"" isEqualToString:str] ||
[[str stringByReplacingOccurrencesOfString:#" " withString:#""] length] == 0||
[str isEqualToString:#"(null)"]
|| ([str respondsToSelector:#selector(length)] && [(NSData *) str length] == 0)
|| ([str respondsToSelector:#selector(count)] && [(NSArray *) str count] == 0)
|| [[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0;
}
actually I just fixed this problem by turning it around like so
-(BOOL) isNotNullOrWhiteSpace
{
return [self length] != 0 && [[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] != 0;
}
so instead of isNullOrWhiteSpace it's isNotNullOrWhiteSpace.
Here's my method of checking null/empty
-(NSString*)NULLInputinitWithString:(NSString*)InputString
{
if( (InputString == nil) ||(InputString ==(NSString*)[NSNull null])||([InputString isEqual:nil])||([InputString length] == 0)||([InputString isEqualToString:#""])||([InputString isEqualToString:#"(NULL)"])||([InputString isEqualToString:#"<NULL>"])||([InputString isEqualToString:#"<null>"]||([InputString isEqualToString:#"(null)"])||([InputString isEqualToString:#"NULL"]) ||([InputString isEqualToString:#"null"])))
return #"";
else
return InputString ;
}
Have you thought about creating a class method on a category that extends NSString?
NSString+NSStringExtensions.h
#import <Foundation/Foundation.h>
#interface NSString(NSStringExtensions)
+(BOOL)isNilOrEmpty:(NSString*)string;
#end
NSString+NSStringExtensions.m
#import "NSString+NSStringExtensions.h"
#implementation NSString(NSStringExtensions)
+(BOOL)isNilOrEmpty:(NSString*)string
{
if (nil == string)
{
return YES;
}
if (string.length == 0)
{
return YES;
}
return NO;
}
#end
Then you use it like this:
#import "NSString+NSStringExtensions.h"
...
NSLog([NSString isNilOrEmpty:#""] ? #"1":#"0");

Check if key exists in NSDictionary is null or not

I did search on how to check if NSDictionary key exists or not and came up with the solution. But still it throws me an error saying adding null value to the key.
I am not sure if my code is correct or not. If anyone has any idea about this can help me.
NSDictionary *result;
id myImageURL = [result objectForKey:#"url"];
if ((NSNull *)myImageURL == [NSNull null])
myImageURL = #"";
id myImage = [result objectForKey:#"image"];
if ((NSNull *)myImage == [NSNull null])
myImage = #"";
Check if null add nothing and if not add the value. But it still gives me an error dont know why.
/****OUTPUT*****/
2011-08-11 14:56:06.668 Tab_Table_Win[6510:207] RESULTS : {
image = "<UIImage: 0xbc332c0>";
url = "http://a3.twimg.com/profile_images/999228511/normal.jpg";
}
2011-08-11 14:56:06.669 Tab_Table_Win[6510:207] url : http://a3.twimg.com/profile_images/999228511/normal.jpg
2011-08-11 14:56:06.670 Tab_Table_Win[6510:207] IMage : <UIImage: 0xbc332c0>
/*****Breaks Here ***/
2011-08-11 14:56:06.876 Tab_Table_Win[6510:207] RESULTS : {
}
2011-08-11 14:56:06.878 Tab_Table_Win[6510:207] url : (null)
2011-08-11 14:56:06.879 Tab_Table_Win[6510:207] IMage : (null)
2011-08-11 14:56:06.881 Tab_Table_Win[6510:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary setObject:forKey:]: attempt to insert nil key'
Correct answer is :
NSDictionary *result;
NSURL *myImageURL = [result objectForKey:#"url"];
UIImage *myImage = [result objectForKey:#"image"];
/**** Correct way ****/
if (myImageURL != nil && myImage != nil) {
[images setObject:myImage forKey:myImageURL];
}
Thank you for all the explanation.
Tommy explained this perfectly.
What I recommend is create an extension of the NSDictionary class like:
#import <Foundation/Foundation.h>
#interface NSDictionary (Safety)
- (id)safeObjectForKey:(id)aKey;
#end
And the implementation file:
#import "NSDictionary+Safety.h"
#implementation NSDictionary (Safety)
- (id)safeObjectForKey:(id)aKey {
NSObject *object = self[aKey];
if (object == [NSNull null]) {
return nil;
}
return object;
}
#end
And instead of using [dictionary objectForKey:#"keyName"]; in your code, use
[dictionary safeObjectForKey:#"keyName"];
This way, as Tommy explained, you'd be sending a method call to a nil which wouldn't crash the app but your object would get a nil value.
Hope this helps.
Whenever I try to check if an object being returned from a dictionary is null, I do this:
id obj = [myDictionary objectForKey:entityKeyName];
if (obj == [NSNull null]) {
// do something
}
Then in your code, it would be:
NSDictionary *result;
NSString *myImageURL = [result objectForKey:#"url"];
if (myImageURL == [NSNull null])
myImageURL = #"";
That's what I would do in your code.
Also, just making sure, is the NSDictionary result defined? In your code, it doesn't have anything it's being set to. It's just being defined as variable you plan on using called results
the answer below worked for me:
https://stackoverflow.com/a/2784675/936957
if ([dictionary objectForKey:key]) {
// previously stored data for "key"
}
Also note that you can get array of the keys in a dictionary using
[dictionary allKeys]
If an object doesn't exist for a key, NSDictionary will return nil. An NSNull is an actual object, and therefore a distinct thing. It's like the distinction between being able to record that there was a value and the value as null, and not recording whether there was a value. It also rests a bit on you thinking in C terms of the indirection of a pointer to an object rather than just an object, so it's not completely semantically pleasing from that perspective.
In Objective-C, you may send any message to nil and the result is guaranteed to be nil (or 0). So if your code is designed to ensure that you have a safe object reference, as you might in C++, then what you're doing is unnecessary. Compound statements like:
object = [[Type alloc] init];
Are always explicitly safe, even if alloc fails and returns nil. All that'll happen is that the call to init won't do anything at all, and object will end up with the value nil because the result of sending of init to nil is also nil.
That being said, the answers provided by Bill and Emmanuel should be correct. Compare your result either directly to nil or implicitly to zero. If you're getting a crash later on, I'll guess it's because you're expecting myImageUrl and myImage to be types other than NSString (I notice you've used the typeless id in your original code) and sending them a message they don't respond to.
NSDictionary *result;
NSString *myImageURL = [result objectForKey:#"url"];
if (myImageURL == NULL)
myImageURL = #"";
NSString *myImage = [result objectForKey:#"image"];
if (myImageURL == NULL)
myImage = #"";
See if that works, rather than overthinking the NULL class.
this another option:
if (![result objectForKey:#"image"])
{
NSLog(#"doesn't exist");
}
if ([result objectForKey:#"image"])
{
NSLog(#"exist");
}
that was not work for me, i figured it out like this
id myImageURL = [result objectForKey:#"url"];
if ([myImageURL isKindOfClass:[NSNull class]])
myImageURL = #"";
Alright here's the actual answer which #Iomec almost had
UIImage *myImage = ([result objectForKey:#"image"] != [NSNull null] ? [result objectForKey:#"image"] : nil);
That is the actual correct answer because, it comes as null and when you say myImage = [receivedObject...]; then if myImage = nil, you are in effect casting a null value(nil) into a class which is an exception, if not a running bug.
You should:
1) test for NSNull null value
2) if not nil then assign
If you code hasn't bugged out yet, it will in production when you have 8 apps running in the background one day.
I got the same issue with JSONKit. The implementation there is
- (id)objectForKey:(id)aKey
{
[...]
return((entryForKey != NULL) ? entryForKey->object : NULL);
}
So this will definitely return NULL if the object isn't there. I check it like the following
NSArray* array = [myDictionary objectForKey:#"a"];
if((NSNull*)arrays!=[NSNull null])
{
[...]
}
1. Results Dictionary after JSON parsing:
//if hits success
{"result":{"action":"authentication","statusCode":"200","statusMsg":"No
error, operation
successful.","count":1,"data":{"apiToken":"509e6d21-4f69-4ded-9f3d-4537e59e6a3a","userId":8,"role":"Bidder","firstName":"bidder","lastName":"bidder","emailAddress":"1cbrecbill#wricapitalgroup.com","countiesCovered":"21,16,11,1,2,14,32,3,4,25,13,15,5,41,43,6,12,7,24,39,17,36,42,44,29,40,8,18,19,27,9,28,23,10,33,26,35,20,30,22,34,31"}}}
//Data is Dictionary inside Result
-----------------------------------------------------------------------
I had an error showing : NULL DATACould not cast value of type 'NSNull' (0xda7058) to 'NSDictionary' (0xda6d74) and the result was
the following.
({"result":{"action":"authentication","statusCode":"204","statusMsg":"Invalid
Username or Password","count":null,"data":null}})
I fixed the Null check of dictionary.
if (result.objectForKey("data") is NSNull)
{
print ("NULL DATA")
}
else
{
let data = result["data"]as! NSDictionary
print (data)
}
Might want to add a bit more safety by checking to make sure it is NOT a string instead of just checking if it IS a nil. (To make sure it is not a number or anything else you might not want.)
id myImageURL = [result objectForKey:#"url"];
if (![myImageURL isKindOfClass:[NSString class]]) {
myImageURL = #"";
}
When you call objectForKeyin nullable dictionary, app gets crashed so I fixed this from this way to avoid from crash.
- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
id object = dictionary;
if (dictionary && (object != [NSNull null])) {
self.name = [dictionary objectForKey:#"name"];
self.age = [dictionary objectForKey:#"age"];
}
return self;
}

[NSNull isEqualToString:]

Im trying to set a string to "No Display name if [object objectForKey#"display_name"] is NULL". It crashing with this in the log
2011-06-16 10:58:36.251 BV API[15586:ef03] displayNameType is: NSNull
2011-06-16 10:58:36.251 BV API[15586:ef03] +[NSNull isEqualToString:]: unrecognized selector sent to class 0x1228c40
2011-06-16 10:58:36.253 BV API[15586:ef03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSNull isEqualToString:]: unrecognized selector sent to class 0x1228c40'
*** First throw call stack:
(0x1198f1c 0x132b52e 0x119bb2b 0x10f3076 0x10f2bb2 0x116d9 0x112ad 0x8b0e17 0x8b9783 0x8b43ae 0x8b9d20 0xb6312b 0x815c35 0xac2e1e 0x8b7583 0x8b771d 0x8b775d 0xc1b5 0x7ed84c 0x7ed7e2 0x89477a 0x894c4a 0x893ee4 0x813002 0x81320a 0x7f960c 0x7ecd52 0x211b8f6 0x116831a 0x10c3d07 0x10c1e93 0x10c1750 0x10c1671 0x211a0c3 0x211a188 0x7eac29 0x1b29 0x1aa5)
terminate called throwing an exceptionsharedlibrary apply-load-rules all
Current language: auto; currently objective-c
NSString *displayNameType = (NSString *)[[object objectForKey:#"display_name"] class ];
NSLog(#"displayNameType is: %#", displayNameType);
NSString *displayNameString = [NSString stringWithFormat:#"%#", [object objectForKey:#"display_name"]];
displayNameString = [displayNameString uppercaseString];
if ([displayNameType isEqualToString:#"NSNull"]) {
NSLog(#"dnt is null");
NSString *displayNameString = #"No Display Name";
displayNameString = [displayNameString uppercaseString];
}
A cast will not change an object class (type).
You have to manage the case when your value is [NSNull null] with something like :
id displayNameTypeValue = [object objectForKey:#"display_name"];
NSString *displayNameType = #"";
if (displayNameTypeValue != [NSNull null])
displayNameType = (NSString *)displayNameTypeValue;
I created a category on NSNull, works well for me:
#interface NSNull (string)
-(BOOL) isEqualToString:(NSString *) compare;
#end
#implementation NSNull (string)
-(BOOL) isEqualToString:(NSString *) compare {
if ([compare isKindOfClass:[NSNull class]] || !compare) {
NSLog(#"NSNull isKindOfClass called!");
return YES;
}
return NO;
}
#end
You might want something like this:
NSString *displayNameType = NSStringFromClass([[object objectForKey:#"display_name"] class]);
And btw in your question, it shouldn't read "if it's NULL", but rather "if it's an NSNull instance".
I'll throw in my answer to clarify a bit. The problem is that the object in the NSDictionary has [NSNull null] value (slightly different to both nil and NULL). The issue comes from some libraries (a particular JSON parser comes to my mind) set the value for some keys with NULL value to [NSNull null]. Why? Because sometimes it is needed to differentiate in a NSDictionary the case when a key is not present from the case when the key has NULL value. In an NSDictionary there is no way of telling, but JSON structures do convey such difference. When you get a a variable that comes from a library or parser that does that the value may be [NSNull null]. NSNull is a singleton thus just checking for equality (pointer equality) is enough. For example I would do:
NSString *value = [object objectForKey:#"display_name"];
if (value && value != [NSNull null]){
// Here I have the value I expect
// Do something
}else{
// The value is null ... don't display
}
To my experience, the font may be well missing. If you got the problem, you could check where you set the new font and if it exists.
let font = UIFont.init(name:"YOUR_FONT_NAME", size: 16) -> is it nil or not ?
Detect whether or not the object is null instead of trying to infer from the class name.
// if you're key may not exist (NSDictionary will return nil... not sure what type
// you are using
if (![object objectForKey:#"display_name"]){
// ...
}
// or if the value may actually be an NSNull object
if ([[object objectForKey:#"display_name"] == (id)[NSNull null]){
// ...
}
I haven't tested the second argument, but look here for more about testing null.
I solved this by doing a check against [NSNull null]. The code I used in my app:
_lblBusinessName.text = _business.BusinessName != [NSNull null] ? _business.BusinessName : #"";
However XCode threw some warnings so to get rid of those I casted to an NSObject* type, like this:
_lblBusinessName.text = **(NSObject*)**_business.BusinessName != [NSNull null] ? _business.BusinessName : #"";

Why isn't this conditional statement working with NSUserDefault?

I'm having a problem getting one of my conditional statements to display data correctly. Here is the code I'm working with:
NSUserDefaults *pickerDefaults = [NSUserDefaults standardUserDefaults];
NSString *myString = [pickerDefaults stringForKey:#"userpicker"];
NSString *string = #"Name1";
NSLog(#"%#",myString); //This prints out Name1
NSLog(#"%#",string); //This also prints out Name1
if (myString == string) {
[pickerArray addObject:#"Name Other"];
}
else {
return;
}
I can't get this if statement to add that object to the UIPicker eventhough both strings are equal to each other. However, if I change it to not equal to != then it display's the object in the UIPickerView. I don't understand what I'm doing wrong. Any help would be great. Thanks.
To compare string objects, don't use their pointer values, but compare using
[string isEqualToString:myString]
if (myString == string) // Wrong : It compares address of two NSStrings
if ([myString isEqualToString:string]) // This compares values of NSStrings
{
}