Junior — Middle
What is the difference between the data type NSInteger and the class NSNumber in Objective-C?
sobes.tech AI
Answer from AI
NSInteger is a primitive data type (a typedef for int or long depending on the architecture) used to store integer values. It is not an object and operates at the stack level.
NSNumber is a wrapper class (an object) that allows storing numeric values (including NSInteger, float, double, etc.) as objects. This is useful when you need to store numbers in collections that only work with objects, such as NSArray or NSDictionary.
Example:
NSInteger myInt = 42; // simple integer type
NSNumber *myNumber = @(myInt); // wrapper object for the number
// Using NSNumber in an array
NSArray *array = @[myNumber];
// Retrieving the value from NSNumber
NSInteger value = [myNumber integerValue];
Thus, NSInteger is a basic numeric type, and NSNumber is an object that encapsulates a number for use in an object-oriented context.