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 (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to