Value Objects

When you're building your own model, view, and controller classes, you'll often have to choose how to store data within those classes. Since Objective-C is built on top of C, all the primitive data types are available. The question is, then, whether to use integers, floating-point numbers, and character arrays or to use a class that wraps those same primitive values in an object.

Let's Get Primitive

There's no harm in using a primitive type in your object's instance variables. In fact, it can often make things much easier for your implementation, because you don't have to worry about retaining and releasing objects. For example, if you're just keeping track of a counter, you don't need to add the overhead of an object.

Tip

One of the most important counters in Cocoa, the retainCount in NSObject, is defined as an unsigned integer (NSUInteger). Although the keywords NSInteger and NSUInteger look like they could be class names, they're really just type definitions used throughout Cocoa Touch.

typedef int NSInteger;
typedef unsigned int NSUInteger;

Other examples of commonly used type definitions are NSRange, a structure that defines a range of data, and NSTimeInterval, a floating-point value that represents a period of time.

Instance variables that use primitive types are defined a little bit differently than instance variables of objects. Since there's no retain or copying involved, they're defined with the assign attribute for the @property. For example, if you had decided ...

Get iPhone App Development: The Missing Manual now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.