How to use NSCoder

前端 未结 4 1978
佛祖请我去吃肉
佛祖请我去吃肉 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:52

    Here is the NSCoding protocal methods from my LogEntry object, you can ignore the switch statement and the schema details though, those are from a base class I have written that allows me to keep sane track of changing data formats.

    Please note that in addition to using decodeObjectForKey: you also need to make sure you retain/copy the given values as they are autoreleased when received.

    - (id)initWithCoder:(NSCoder *)coder {
        self = [super initWithCoder:coder];
    
        if (self != nil) {
            switch ([schemaVersion intValue]) {
                case 2:
                    filepath = [[coder decodeObjectForKey:@"filepath"] copy];
                    identifier = [coder decodeInt64ForKey:@"identifier"];
                    level = [coder decodeIntForKey:@"level"];
                    lineNumber = [[coder decodeObjectForKey:@"lineNumber"] retain];
                    message = [[coder decodeObjectForKey:@"message"] retain];
                    timestamp = [[coder decodeObjectForKey:@"timestamp"] retain];
                    break;              
                default:
                    [self release], self = nil;
                    break;
            }
        }
    
        return self;
    }
    
    - (void)encodeWithCoder:(NSCoder *)coder {
        [coder encodeObject:filepath forKey:@"filepath"];
        [coder encodeInt64:identifier forKey:@"identifier"];
        [coder encodeInt:level forKey:@"level"];
        [coder encodeObject:lineNumber forKey:@"lineNumber"];
        [coder encodeObject:message forKey:@"message"];
        [coder encodeObject:timestamp forKey:@"timestamp"];
    
        [super encodeWithCoder:coder];
    }
    

提交回复
热议问题