6
NSUInteger index = [self.objects indexOfObject:obj];

if (index == NSNotFound) {
    // Success! Note: NSNotFound internally uses NSIntegerMax
}

if (index == NSUIntegerMax) {
    // Fails!
}

Why? I'm suppose to get an unsigned value as a result of indexOfObject. So, naturally, i was assuming that if the object is not found, it will return NSUIntegerMax instead of NSIntegerMax. Is this a bug, or is there a logical explanation for this behavior.

Mustafa
  • 20,504
  • 42
  • 146
  • 209

3 Answers3

7

Perhaps NSNotFound can be used in contexts that use NSInteger. It is also safer, in case someone declares index as NSInteger instead of NSUInteger.

At most, one could say that it's odd that NSNotFound is defined as NSIntegerMax, but it's certainly not a bug.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
2

Your assumption is just wrong. It returns an NSNotFound, whatever this is now or will be in the future. And it may easily be different on different platforms (i.e. 32 vs 64 bit).

The reason for its existence is to use it. Don't fool yourself with using other constants that might be the same.

Eiko
  • 25,601
  • 15
  • 56
  • 71
  • Well, i believe my assumption was fair, though not accurate. Consider this... `[array count]` returns `NSUInteger`. Now, what if i have more than `NSIntegerMax` objects in array? It should allow more than NSIntegerMax values (though i haven't verified). Now if `NSIntegerMax` value returned by `[array indexOfObject:myObject]` is a valid value then a check for NSNotFound will/should fail. I must be missing something here. – Mustafa Jul 05 '11 at 11:38
  • 2
    @Mustafa: You can't have `NSIntegerMax` objects in an array, since this would consume about double the address space on a 32-bit architecture and about four times the address space on a 64-bit architecture. – Marcelo Cantos Jul 05 '11 at 11:42
  • Marcelo is right, check what you are comparing using the debugger. See my post http://stackoverflow.com/questions/6970953/convert-nsinteger-to-nsuinteger/9422965 – tgunr Feb 23 '12 at 23:20
0

An NSUInteger is unsigned (the 'U') while an NSInteger is signed.

You can still compare the values of an unsigned and a signed integer. Assuming that NSNotFound is actually equal to NSUIntegerMax is probably a mistake. In fact it is defined as equal to NSIntegerMax in NSObjCRuntime.h.

Mark Granoff
  • 16,878
  • 2
  • 59
  • 61
  • You misunderstood. I'm/I was assuming that indexOfObject will return NSUIntegerMax incase the object is not found, because it returns NSUInteger. I know that NSNotFound uses NSIntegerMax internally. – Mustafa Jul 05 '11 at 11:29