Re: Why does NSArray count return NSUInteger?
Re: Why does NSArray count return NSUInteger?
- Subject: Re: Why does NSArray count return NSUInteger?
- From: Roland King <email@hidden>
- Date: Mon, 30 May 2011 19:28:21 +0800
> In what contexts is that output going to be used?
> I think that like me people will tend to use it in contexts to do with accessing array elements
> e.g. x = [ary objectAtIndex:[ary count]-2];
well if you haven't already confirmed that [ary count ] can never be less than 2, or checked that [ ary count ] is larger than or equal to 2, or then you shouldn't be trying to get the element at ( [ ary count ] - 2 ), you're going to fail whatever the data type is, that's a logic error.
> or modifying behaviour according to array size
> e.g. if(k1 < ([ary count] - k2)) {…
again - if you don't already know that [ ary count ] >= k2, you should't subtract k2 from it. if you don't know and want to do that statement with one check use
If( ( k1 + k2 ) < [ ary count ] ) ..
> If we know that a variable is never going to return a negative value and that it is predominantly going to be used in an arithmetic context why force the programmer to think about coercing the type on each occasion of its use when failure to do so risks malfunction?
You don't need to coerce it. NSUInteger works perfectly well in an arithmetic context. The programmer needs to ensure that they treat the data type within its limits. You can't add 20,000,000 to an unsigned char and expect it to work, similarly here you have to be aware of the kind of variable you have and treat it appropriately. That If( ( k1 + k2 ) < [ ary count ] ) is a good example of that.
>
> So was it really just because the number of array elements is never -3 that the Cocoa developers decided to make NSArray count return type NSUInteger?
Yes. Because NSArrays cannot have less than 0 elements, so there is no point at all having the size of an array have a potential negative domain. It's meaningless. They didn't use a double or a float for size either, because you can't have 2.5 things in an array or look up the point at Array[ 23.4 ], well not with this kind of array. They used the datatype which maps onto the thing they are describing, array elements are non-negative integers, so they used NSUInteger.
>
> Julius
>
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden