How to use NSCoder

前端 未结 4 1981
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-03 03:22

I am developing iphone application.

I use NSCoder.

MyApplication.h

#define ITEMS_KEY @\"items\"
#define CATEGORIES_KEY @\"categories\"


#imp         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-03 03:50

    I wrote a helper function for using NSCoding. It's a part of VSCore Library. Check it out here:

    @interface QuickCoding : NSObject
    
    + (void)quickEncode:(NSObject*)object withEncoder:(NSCoder*)encoder;
    + (void)quickDecode:(NSObject*)object withDecoder:(NSCoder*)decoder;
    
    @end
    

    And the .m file:

    #import "QuickCoding.h"
    #import "ReflectionHelper.h"
    
    #define QUICK_CODING_HASH   @"h4"
    
    @implementation QuickCoding
    
    + (void)quickEncode:(NSObject*)object withEncoder:(NSCoder *)encoder{
        NSArray *codingKeys = [ReflectionHelper fieldsList:[object class]];
        NSUInteger hash = [[codingKeys componentsJoinedByString:@""] hash];
        [encoder encodeObject:@(hash) forKey:QUICK_CODING_HASH];
    
        [codingKeys enumerateObjectsUsingBlock:^(NSString *key, __unused NSUInteger idx, __unused BOOL *stop) {
            id val = [object valueForKey:key];
            if ([val conformsToProtocol:@protocol(NSCoding)]){
                [encoder encodeObject:val forKey:key];
            }
        }];
    }
    
    + (void)quickDecode:(NSObject*)object withDecoder:(NSCoder *)decoder{
        NSArray *codingKeys = [ReflectionHelper fieldsList:[object class]];
        NSUInteger hash = [[codingKeys componentsJoinedByString:@""] hash];
        NSUInteger decodedHash = [[decoder decodeObjectForKey:QUICK_CODING_HASH] unsignedIntegerValue];
        BOOL equalHash = hash == decodedHash;
    
        [codingKeys enumerateObjectsUsingBlock:^(NSString *key, __unused NSUInteger idx, __unused BOOL *stop) {
            id val = [decoder decodeObjectForKey:key];
            if (equalHash || val){
                [object setValue:val forKey:key];
            }
        }];
    }
    
    @end
    

    Full code is here: https://github.com/voipswitch/VSCore/tree/master/VSCore/Storage

提交回复
热议问题