简体   繁体   中英

Determine if NSUInteger has a value or is nil

I'm trying to use a HKAnchoredObjectQuery on iOS.

To do so I have to provide an anchor to the query which in this case is a NSUInteger . I want to save this integer for queries in the future in the NSUserDefaults and just simply want to use

if(anchor != nil) { // do stuff }

But the complier tells me that I'm not allowed to do this because I'm comparing a integer to a pointer and I understand why I'm not able to do this but I don't know how to do it.

The error code is this

Comparison between pointer and integer ('NSUInteger' (aka 'unsigned long') and 'void *')

Does anyone know how I'm able to determine if my anchor has a value or not?

NSUInteger is a primitive type, not an object type. NSNumber is an object type. For an NSNumber object, you can check whether it is nil or not. An NSUInteger is never nil because it is an integer, not a pointer.

Many functions that return NSUInteger as a result for a search return the constant NSNotFound if the search failed. NSNotFound is defined as a very large integer (2^31 - 1 for 32 bit, 2^63 - 1) for 64 bit).

NSUInteger is not an object and cannot be compared to nil. In over-simplistic terms, an object is a pointer to a memory location that may contain an value or be nil . NSUInteger is just a value. It may be 0 , or some other value that you don't expect, but it will have a value.

An NSUInteger cannot be nil because it is not an object. The default value on creation would be zero. To save in NSUserDefaults , you could store it as an NSNumber , which could be checked for nil later.

To store it in NSUserDefaults :

NSNumber *aNumber = @(anchor);
[[NSUserDefaults standardUserDefaults] setObject:aNumber forKey:aKey];

To get the anchor back from NSUserDefaults :

NSNumber *aNumber = [[NSUserDefaults standardUserDefaults] objectForKey:aKey];
if (aNumber != nil) {
    NSUInteger anchor = [aNumber integerValue];
}

NSUInteger or simply int are basically primitive data types and they should be compared with the integer values with in the range of the corresponding data types. nil is used with referenced objects.

In your case, as anchor is NSUInteger so you should use integer value for comparison in place of nil as-

if(anchor != 0) {
// do stuff
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM