Understanding Objective-C Number Objects

From Techotopia
Revision as of 15:12, 5 November 2009 by Neil (Talk | contribs) (New page: In Objective-C 2.0 Data Types we looked at the basic data types supported by Objective-C including a range of types for working with numbers. These data types are what is known as ''pr...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

In Objective-C 2.0 Data Types we looked at the basic data types supported by Objective-C including a range of types for working with numbers. These data types are what is known as primitive types in that they simply allow values to be stored in memory and are not objects.

In order to work with numbers in object form, Objective-C provides the NSNumber class. This class is one of the stranger additions to the Objective-C language in that functionally speaking, number objects don't give you anything that you can't already do with primitive number types. It seems the sole purpose of the NSNumber class is to allow numbers to be stored in an NSArray object, which only handles objects.

In this chapter we will take a look at the NSNumber class and provide an overview of how to work with number objects.

Creating and Initializing NSNumber Objects

As previously discussed, the primary purpose of the NSNumber class is to allow the storage of primitive numerical data in the form of an object. The NSNumber class is able to store signed and unsigned char, short, integer, int, long and long long data types and also float, double and Bool values.

The NSNumber class contains a set of class methods designed specifically for creating objects and initializing them with values of a particular numerical data type. The naming convention for these class methods is as follows:

numberWith<Unsigned><Type>

The full list of creation and initialization methods is as follows:

numberWithBool numberWithChar numberWithDouble numberWithFloat numberWithInt numberWithInteger numberWithLong numberWithLongLong numberWithShort numberWithUnsignedChar numberWithUnsignedInt numberWithUnsignedInteger numberWithUnsignedLong numberWithUnsignedLongLong numberWithUnsignedShort

Because these are class methods, rather than instance methods, they are called on the class rather than on an existing object. For example, to create an NSNumber object called myNumber we could write the following code: