Want to compare string with null iOS sdk - ios

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

Related

Objective C syntax issue related to parameter not getting right data

I've been working on a project implementing Hola CDN framework. I'm now running into an issue that I can't pass on current date to the parameter programDay and I traced the source code and I found the below line. What does this below line mean?
self.programDay = ![dict[GETPROGRAMLISTDATA_PROGRAMEDAY] isEqual:[NSNull null]] ? dict[GETPROGRAMLISTDATA_PROGRAMEDAY] : nil;
What's NSNull
[NSNull null] doesn't equal to nil. It means empty value. For example,
#[[NSNull null]].count equals to 1. NSNull is used as placeholder in NSArray and NSDictionary. It means nil.
For your question
This line is used to replace NSNull with nil.
self.programDay = ![dict[GETPROGRAMLISTDATA_PROGRAMEDAY] isEqual:[NSNull null]] ? dict[GETPROGRAMLISTDATA_PROGRAMEDAY] : nil;
This line means that if [dict[GETPROGRAMLISTDATA_PROGRAMEDAY] has empty value or null value the nil would be assign to self.programDay as there would be value of [dict[GETPROGRAMLISTDATA_PROGRAMEDAY] will be assign to self.programDay. Usually (null) value is return from webservice if that value is not presented in database on server.

xcode - compare result of NSDictionary object with integer

i have simple question about how to compare result of NSDictionary with integer
i print on log the data in key result its equal 0
log
2014-09-17 10:25:42.848 School Link Version 2[1027:60b] the result are 0
but when i compare it , its dosnt work
i wish know why , its simple compare
-(void) didFinish:(NSMutableData *)data{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"the result are %#",json[#"result"]);
if (json[#"result"] == 0) {
[[self _delegate] didFailWithMessage:json[#"message"]];
return;
}
}
You compare string to int, you need to convert string value to int:
if ([json[#"result"] intValue] == 0) {
First, your code will crash if the server didn't give you a dictionary, but an array. Since it is out of your control what the server sends, your app can crash at any time. You can check that you received a dictionary by writing
if (! [json isKindOfClass:[NSDictionary class]]) { /* Handle error */ }
Once you know it's a dictionary, you need to check what kind of item you actually expect. Do you expect a string, an integer, a decimal number? You should have a spec for the JSON data. If you are not sure, or want to be flexible, both strings and numbers produce an object that will support messages like "doubleValue", "integerValue" etc. Extract the item and assign it to a pointer of a class supporting "doubleValue", for example.
NSString* result = json [#"result"];
if (! [result respondsToSelector:#selector (doubleValue)]) { /* Handle error */ }
Now you can check whether the doubleValue is equal to 0.
if ([result doubleValue] == 0.0) { ... }
intValue will fail if the value is a large integer.
integerValue is slightly better but will fail if the value is for example the number 0.3 or the string "0.3". Everything will fail if the result is a string with the contents "Hello". You also should figure out what you want to do if result == nil (there was no key "result") or if result == [NSNull null] (there was a key:value pair "result": null)
The code that you actually wrote compared the object stored at the key "result" with 0, that is with a nil pointer. The object will be nil if the JSON data doesn't contain anything under that key. For example,
if (json [#"RandomNonsenseKey"] == 0)
will most likely succeed (unless your server sent data with a key RandomNonsenseKey).

how to Check NSString is null or not [duplicate]

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

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