How to store a NSUInteger using NSCoding?

后端 未结 4 1270
攒了一身酷
攒了一身酷 2021-02-05 04:03

How do I store a NSUInteger using the NSCoding protocol, given that there is no method on NSCoder like -encodeUnsignedInteger:(NSUIn

4条回答
  •  深忆病人
    2021-02-05 04:39

    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  {
        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
    

提交回复
热议问题