Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the largest value an NSNumber can store?

What's the largest value an NSNumber can store?

// ok
    NSNumber *value = @(1 << 31); 

// gives compiler error, so max NSNumber is 32-bit uint?
    NSNumber *value = @(1 << 32); 
like image 570
Boon Avatar asked Feb 21 '13 05:02

Boon


People also ask

Is NSNumber integer?

NSNumber provides readonly properties that return the object's stored value converted to a particular Boolean, integer, unsigned integer, or floating point C scalar type.

Why use NSNumber?

The purpose of NSNumber is simply to box primitive types in objects (pointer types), so you can use them in situations that require pointer-type values to work. One common example: you have to use NSNumber if you want to persist numeric values in Core Data entities.

Is NSInteger primitive?

As said by others before, NSNumber is an NSObject subclass. It is not a C primitive (like int, unsigned int, float, double, etc.) NSInteger , CGFloat , NSUInteger are simple typedefs over the C primitives. The need for NSNumber arises from the need to use numbers as parameters to APIs that require Objects.

What is __ NSCFNumber?

NSCFNumber is a concrete, "private" implementation of a class in that cluster.


1 Answers

NSNumber is actually a class cluster, meaning that when you create an instance you may be getting any of a variety of concrete subclasses, each capable of storing a different kind of numeric type. The actual types available, and their sizes, may be machine-dependent.

Looking at the NSNumber documentation shows you the different kinds of numbers you can store: the two largest integer options would be +numberWithLongLong: (or +numberWithUnsignedLongLong:), which stores a long long, and +numberWithInteger: (or +numberWithUnsignedInteger:), which stores an NSInteger. The maximum NSNumber values are therefore limited by these types.

The Foundation documentation states:

When building 32-bit applications, NSInteger is a 32-bit integer. A 64-bit application treats NSInteger as a 64-bit integer.

The compiler is smart and will create an NSNumber of the same type as your numeric literal. As mentioned in the comments above, you can use @(1ULL << 32) if your machine has an unsigned long long type with more than 32 bits.

Furthermore, NSNumber is toll-free bridged to CFNumber, meaning you can try out functions like CFNumberGetByteSize() for yourself — and have a look at the Number Types section of the CFNumber documentation. You'll see these are basically the same as the NSNumber options.

Additionally, the NSDecimalNumber class, a subclass of NSNumber, provides the +maximumDecimalNumber method which you can use to find the maximum value that can be stored in an NSDecimalNumber. NSDecimalNumber, and the floating-point types, may be able to store bigger numbers than the integer types, though with decreasing precision.

like image 69
jtbandes Avatar answered Sep 18 '22 19:09

jtbandes