So here I was trying to make a Mac produce the little endian binary format that the Momento needs and so I thought I’d better extend NSMutableData to give it some LittleEndian “append” capability. So, I set up my class and the inheritance from but I kept getting an error that -length was only enabled for the abstract class. Then I discovered categories.

You can declare a new class as a category of an existing class (the convention is to name your files baseclass+category.{m,h}:

@interface NSMutableData (endian)

- (void)appendLittle16:(const uint16_t)value;
- (void)appendLittle32:(const uint32_t)value;

@end

As long as you import this header and link the implementation, your NSMutableData objects suddenly have this extra capability.

Instead of doing things with [super] as you normally do with an inherited class, you operate on [self].


@implementation NSMutableData (endian)

- (void)appendLittle16:(const uint16_t)value
{
uint16_t little16 = CFSwapInt16HostToLittle(value);
[self appendBytes:&little16 length:sizeof(little16)];
}

This makes the code to create packets for the Momento much simpler:

NSMutableData *data;

data=[[NSMutableData alloc] initWithCapacity:20];
[data appendLittle32:2];
[data appendBytes:&UUID length:sizeof(uuid_t)];