discuss-gnustep
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: NSInteger vs. NSUInteger


From: Richard Frith-Macdonald
Subject: Re: NSInteger vs. NSUInteger
Date: Sun, 10 Feb 2013 06:37:11 +0000

On 9 Feb 2013, at 18:11, Sebastian Reitenbach wrote:

> Hi,
> 
> when I see something like this for example in ProjectCenter:
> 
> - (NSInteger)numberOfRowsInTableView: (NSTableView *)aTableView
> {
>  return [docTypesItems count];
> }
> 
> where docTypesItems is a NSMutableArray. I see many of the GUI elements
> use NSInteger. But for example NSArray, or NSDictionary count return
> NSUInteger.
> 
> When I see above statement, how is best way to proceed to not for
> example return a too large NSUInteger, which would convert into
> a negative NSInteger?
> 
> Since most of the time I see contents of tables, browsers and whatnot
> stored in NSArrays or NSDictionaries, nearly everywhere I came across
> I see this potential trouble with the signed vs. unsigned 
> discrepancies when setting it up in the GUI.
> 
> Also often I see some of those results then compared, actually comparing
> a NSUInteger against a NSInteger. When one is too large, or the other
> negative, funny things may happen.
> 
> Is there some best practices, how to handle that? Or is there something in
> the runtime, I am not aware of, that takes care about it?

Well, there are two good things:

1. A direct equality test against NSNotFound will work for both NSInteger and 
NSUInteger, so that's OK.

2. in most contexts in the GUI, it's safe to assume that no data structure will 
contain more than two billion (2^31) elements  ... so you don't have to worry 
about things like array counts returning values which would turn negative when 
converted.  Generally, if you had anything even remotely close to that number 
of elements in a GUI data structure, your app would be effectively dead anyway.

Anywhere that those two cases don't apply, you need to check the value of 
NSUInteger before you treat it as an NSInteger.
So, while it's good to review these cases, and important to treat them with 
care, it's usually fine to simply cast the unsigned value to be a signed one.




reply via email to

[Prev in Thread] Current Thread [Next in Thread]