Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax to check if NSInteger is nil or not?

Tags:

objective-c

The following is returning an error because evidently I cannot compare an NSInteger or int to nil. Can anyone suggest syntax to do this

NSInteger *lastID = [[NSUserDefaults standardUserDefaults] integerForKey:@"lastID"]==nil ? @1 : [[NSUserDefaults standardUserDefaults] integerForKey:@"lastID"];
like image 755
user1904273 Avatar asked Dec 24 '22 14:12

user1904273


2 Answers

NSInteger lastID = [[NSUserDefaults standardUserDefaults] integerForKey:@"lastID"] == 0 ? 1 : [[NSUserDefaults standardUserDefaults] integerForKey:@"lastID"];

NSInteger is a primitive type. nil is for objects. 0 check, checks is your userDefaults' integer value assigned a value. If it didn't assigned, it returns 0.

like image 166
Candost Avatar answered Dec 28 '22 08:12

Candost


NSInteger is a primitive type, not an object. I'm quite sure that an NSInteger* is not what you want, but an NSInteger. integerForKey returns an NSInteger, not an NSInteger*.

like image 40
gnasher729 Avatar answered Dec 28 '22 10:12

gnasher729