Sweet, Sweet Cocoa

SO SWEET!

0 notes &

Simple primitives container in Objective-C

Today’s post deals with a small pet-peeve I have with ObjC so far: using NSArray to store primitives (wrapped and unwrapped via NSNumbers) is rather cumbersome. Using malloc‘ed arrays is also inconvenient to pass around between objects, since they are not reference-counted and don’t carry their length with them.

After reading this article about emulating templates with C macros, I implemented a small set of fixed-length container classes for primitives, with a template-like set of macros.

The macros were used to generate containers for all primitives (short, int, long, long long, char and unsigned variants, BOOL, float, double) in immutable and mutable flavors. The containers can return the primitive itself, or an autoreleased NSNumber instance that wraps the primitive. The interface for PCMutableDoubleArray, for instance, looks like this:

// Immutable interface
- (id) initWithLength: (unsigned int) num; 
- (id) initWithLength: (unsigned int) num andDoubles: (double) double_0, ...;
- (double) doubleAtIndex: (unsigned int) index; 
- (double*) array;
- (unsigned int) count;
- (unsigned int) length;
- (NSNumber*) numberAtIndex: (unsigned int) index;

// Mutable interface
- (void) setNumber: (NSNumber*) number atIndex: (unsigned int) index;
- (void) setDouble: (type) aDouble atIndex: (unsigned int) index;
- (void) setDoubles: (int) length, ...;
- (void) setDoublesFromArray: (PCDoubleArray*) arr;

A .zip archive of the containers is available here (BSD licensed).