Search code examples
iosobjective-cnsnumber

When would you use NSNumber literal to create encapsulated character values?


I'm just going through Apple's iOS development tutorial at the moment and reading the chapter on the Foundation framework and value objects.

Just on the NSNumber class, it says:

You can even use NSNumber literals to create encapsulated Boolean and character values.

NSNumber *myBoolValue = @YES; NSNumber *myCharValue = @'V';

I'm just wondering, when, or why, or in what scenario, might you want to use NSNumber for a character value rather than using NSString, say?


Solution

  • An NSNumber is useful for encapsulating primitive values to be inserted into Objective-C collection classes such as NSArray, NSSet, NSDictionary, etc.

    Image a scenario where you would want to iterate over each character in an ASCII string and extract a unique set of vowels used. You can evaluate each character and add it to an NSMutableSet. To do so, you would need to encapsulate each character in an NSNumber as NSMutableSet expects an Objective-C object. This is just one example, but the concept applies to many situations where primitives need to be added into a collection.