NSInteger returning 0 if NSString is NULL
-
13-12-2019 - |
Question
This could be the simplest one but I am not able to find the exact cause. Instead to explain in words following is my code:
NSString *str = @"";
NSInteger tempInteger = [str integerValue];
if (tempInteger == 0)
{
NSLog (@"do something");
}
If NSString
returning NULL
then NSInteger
returning 0 and if NSString
has some value then NSInteger
returning same value.
But when NSString
is NULL
then I want NSInteger
should return NULL
not 0 but I am not able to validation NSInteger
as NULL
.
How can I get NULL
value in NSInteger
if NSString
is NULL?
Solution
NULL
is a pointer; NSInteger is a C primitive that can only hold numbers. It is not possible for an NSInteger to ever be NULL
. (Sidenote: when we speak of Objective-C object pointers, we use nil
rather than NULL
.)
Instead, if you wish to handle only cases where the integer value is 0, but the string is not NULL
, you should change your condition as follows:
if (tempInteger == 0 && str != nil)
However, in your case, the string is not nil
; it is merely an existent--but empty--string. If you wish to also check for that, your condition could become:
if (tempInteger == 0 && [str length] > 0)
This checks both cases because a nil
string will return length 0
. (In fact, any method sent to nil
will return 0
, nil
, 0.0
, etc. depending on the return type.)
OTHER TIPS
Actually you could implement a logic such as this:
- Check if your string is indeed an integer
- Try to convert it
- If it's equal to 0 do something
Something like this would do the trick:
NSString *str = @"";
NSInteger tempInteger = [str integerValue];
NSCharacterSet *cs = [NSCharacterSet decimalDigitCharacterSet];
BOOL safe = [cs isSupersetOfSet:[NSCharacterSet characterSetWithCharactersInString:str]] && str.length > 0;
if (safe && tempInteger == 0)
{
NSLog (@"do something");
}
An integer can only hold numbers an nut null value. In this case you should first check the length of string to check if it's null
NSInteger
is a scalar variable type. The value NULL
(actually nil
in ObjectiveC), indicating a pointer towards the address 0
, when cast to an NSInteger will be 0
.
For accomplishing your task, you will have to compare NSString
against nil
before converting it towards an integer.
if (str == nil)
{
//our string is invalid
}
else
{
tempInteger = [str integerValue];
}