Reputation: 4764
I have a variable in core data. I want to detect for the cases where it is nil zero, null or otherwise does not have a nice value such as 222 or 333.
This should be trivial but I am getting caught up in Objective-C's syntax.
Following code is not working:
if (_item.id!=nil && _item.id!=0) {
//do something
}
Of note id should be an NSNumber.
It is defined as
@property (nonatomic, retain) NSNumber * id;
I should clarify that it is not working when the value logs to console as 0.
Given the way variable types and core data work, I cannot tell you what causes the variable to log to console as '0' but something is causing it to do so. Basically, I want to exclude cases where the value is anything other than a non-zero integer (in mathematical, not computer science terms).
Upvotes: 2
Views: 7136
Reputation: 59
To check the numeric value stored in an NSNumber, you have to call one of the methods which give you a primitive type.
e.g. integerValue, unsignedLongLongValue, doubleValue
To correctly check for nil and a value of 0, you need the following:
if (_item.id != nil && [_item.id intValue] != 0) {
// code here
}
Because sending a message to a nil reference returns 0, you can take a shortcut:
if ([_item.id intValue] != 0)
Upvotes: 0
Reputation: 4105
As this NSManagedObject
is of type NSNumber
, simply check the intValue.
if (!_item.id.intValue){
//Method will stop in here if the id is nil/0 etc.
}
However, it is not recommended to name a variable id
, I suggest you rename it to itemId
In the same way you shouldn't name something 'string
', or 'new
' etc as these conflict with Apple's own native naming policies
Upvotes: 2
Reputation: 7552
To check the numeric value stored in an NSNumber
, you have to call one of the methods which give you a primitive type.
e.g. integerValue
, unsignedLongLongValue
, doubleValue
To correctly check for nil
and a value of 0
, you need the following:
if (_item.id != nil && [_item.id intValue] != 0) {
// code here
}
Because sending a message to a nil
reference returns 0
, you can take a shortcut:
if ([_item.id intValue] != 0) ...
This works because _item.id
has to be non-nil to return a non-zero value from intValue
.
Upvotes: 8