Re: Why does NSArray count return NSUInteger?
Re: Why does NSArray count return NSUInteger?
- Subject: Re: Why does NSArray count return NSUInteger?
- From: Graham Cox <email@hidden>
- Date: Mon, 30 May 2011 21:30:43 +1000
On 30/05/2011, at 9:03 PM, julius wrote:
> Why did Cocoa developers make the count method return NSUInteger?
Because you can't have negative numbers of elements in an array.
It's that simple.
The reason you're running into trouble is not because this type is unsigned, it's because you are doing arithmetic on it based on faulty assumptions. It's an error to assume that an index is valid just because you computed it to be so. It's always potentially buggy to do things like this:
index = [array count] - 10;
without checking whether what you end up with is in fact a valid index.You are not doing any such checking. The choice of an unsigned type by Cocoa engineers does not make this code suddenly wrong, it was always wrong. Accessing an array with an invalid index will throw an exception. Changing the index type to NSInteger wouldn't change that - the computed index is out of range whether it's expressed as a signed (negative) value or a large unsigned positive value.
> 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?
It is not predominantly used in an arithmetic context, it's used to tell you the number of items in the array. You might use it to compute an offset into the array, but I would suggest that is pretty unusual. Coercing the type is not the right thing to do in any case - the type is what the type is (another advantage of using unsigned is that it effectively doubles the array's capacity, not that an array that large would ever be feasible). It's up to you to work with the types provided correctly, not complain that they made a bad design decision when in fact it's your code which is faulty.
The onus is on you to ensure an array index is in range, or else be prepared for an exception. There's no way of twisting the arithmetic that lets you off doing this.
> 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.
--Graham
_______________________________________________
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