Re: Can an NSArray ever have a count of -1?
Re: Can an NSArray ever have a count of -1?
- Subject: Re: Can an NSArray ever have a count of -1?
- From: Charles Srstka <email@hidden>
- Date: Fri, 19 Feb 2016 17:32:16 -0600
> On Feb 19, 2016, at 4:29 PM, Jens Alfke <email@hidden> wrote:
>
> NSInteger is a typedef of ‘long’ in 64-bit, and ‘int’ in 32-bit.
> You’re correct that %d should be used for NSInteger in 32-bit.
The recommended way to use an NSInteger, as per Apple documentation, is to use %ld and explicitly cast it to long.
NSLog(@“foo is %ld”, (long)foo);
This will work regardless of platform.
For NSUInteger, you use %lu and cast to unsigned long.
Source: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW5 <https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW5>
> The whole variable-size NS[U]Integer thing is awful, especially for anyone writing code that needs to support both 32-bit and 64-bit. One trick I recently heard about that helps somewhat is to use %zd and %zu to format it — the ‘z’ modifier indicates the value is a size_t or ssize_t, and it turns out those have the same size as NS[U]Integers.
As long as you cast it as shown above, it’s no issue at all, and it’s better to do that than to rely on implementation details such as these.
> (Here’s one reason NSInteger sucks: the difference in sizes doesn’t make sense for values that don’t refer to memory sizes. For example, is it OK use NSUInteger to store a file size? In a 64-bit process, sure! In a 32-bit one, you’ll be fine until you encounter a file > 4GB long, then you overflow and get the size wrong. Likewise, how about using NSUInteger to store an index into a persistent array? Bad idea if the persistence layer supports >4 billion items, which any real database does.)
In cases where it matters what size the integer is, you should use use an explicitly sized type (like uint64_t, here). For the common case where the size doesn’t really matter, NS(U)Integer will use whatever size of integer the processor natively handles, which is good for performance.
Charles
_______________________________________________
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