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; }
NSCoding is a protocol that you can implement on your data classes to support the encoding and decoding of your data into a data buffer, which can then persist on disk. Implementing NSCoding is actually ridiculously easy — that's why you may find it helpful to use.
The NSCoding protocol declares the two methods that a class must implement so that instances of that class can be encoded and decoded. This capability provides the basis for archiving (where objects and other structures are stored on disk) and distribution (where objects are copied to different address spaces).
An abstract class that serves as the basis for objects that enable archiving and distribution of other objects. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With