Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a NSUInteger using NSCoding?

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; } 
like image 942
Johan Kool Avatar asked Sep 15 '10 06:09

Johan Kool


People also ask

What does NSCoding do?

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.

What is NSCoding in Swift?

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).

What is coder Nscoder?

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+


1 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 
like image 53
Paul Solt Avatar answered Sep 22 '22 04:09

Paul Solt