Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the row property of NSIndexPath a signed integer?

Why is the row property of NSIndexPath a signed integer?

Could it ever take on a "valid" negative value?

enter image description here

edit

I haven't thought about this until today when I set LLVM to check sign comparison. This made the compiler spew out warnings whenever there was indexPath.row <= [someArray count] or similar.

like image 625
MdaG Avatar asked Nov 27 '12 13:11

MdaG


1 Answers

What happens if you use negative numbers?

It isn't wise to use negative values, if you do, you'll get crazy results

NSIndexPath* path = [NSIndexPath indexPathForRow:-2 inSection:0];

The above results in a section of 0, and a row of 4294967294 (which looks like underflow of an NSUInteger to me!) Be safe in the knowledge that this only occurs within the UIKit Additions category, and not within NSIndexPath itself. Looking at the concept behind NSIndexPath, it really doesn't make sense to hold negative values. So why?

(Possible) Reason for why it is so

The core object NSIndexPath from OS X uses NSUIntegers for its indices, but the UIKit Addition uses NSInteger. The category only builds on top of the core object, but the use of NSInteger over NSUInteger doesn't provide any extra capabilities.

Why it works this way, I have no idea. My guess (and I stipulate guess), is it was a naive API slipup when first launching iOS. When UITableView was released in iOS 2, it used NSIntegers for a variety of things (such as numberOfSections). Think about it: This conceptually doesn't make sense, you can't have a negative number of sections. Now even in iOS 6, it still uses NSInteger, so not to break previous application compatibility with table views.

Alongside UITableView, we have the additions to NSIndexPath, which are used in conjunction with the table view for accessing it's rows and such. Because they have to work together, they need compatible types (in this case NSInteger).

To change the type to NSUInteger across the board would break a lot of things, and for safe API design, everything would need to be renamed so that the NSInteger and NSUInteger counterparts could work safely side by side. Apple probably don't want this hassle (and neither do the developers!), and as such they have kept it to NSInteger.

like image 93
WDUK Avatar answered Nov 16 '22 01:11

WDUK