How to store a NSUInteger using NSCoding?

Viewed 8802

How do I store a NSUInteger using the NSCoding protocol, given that there is no method on NSCoder like -encodeUnsignedInteger:(NSUInteger)anInt forKey:(NSString *)aKey like there is for NSInteger?

The following works, but is this the best way to do this? This does needlessly create objects.

@interface MYObject : NSObject <NSCoding> {
    NSUInteger count;
}  

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:[NSNumber numberWithUnsignedInteger:count] forKey:@"count"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    self = [super init];
    if (self != nil) {
        count = [[decoder decodeObjectForKey:@"count"] unsignedIntegerValue];
    }
    return self;
}
4 Answers

NSNumber has a lot of methods to store/retrieve different sized and signed types. It is the easiest solution to use and doesn't require any byte management like other answers suggest.

Here is the types according to Apple documentation on NSNumber:

+ (NSNumber *)numberWithUnsignedInteger:(NSUInteger)value
- (NSUInteger)unsignedIntegerValue

Yes your code example is the best way to encode/decode the NSUInteger. I would recommend using constants for the key values, so you don't mistype them and introduce archiving bugs.

static NSString * const kCountKey = @"CountKey";

@interface MyObject : NSObject <NSCoding> {
    NSUInteger count;
}  

@end

@implementation MyObject

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:[NSNumber numberWithUnsignedInteger:count] forKey:kCountKey];
}

- (id)initWithCoder:(NSCoder *)decoder {
    self = [super init];
    if (self != nil) {
        count = [[decoder decodeObjectForKey:kCountKey] unsignedIntegerValue];
    }
    return self;
}
@end
Related