美文网首页OS X编程
Objective-C Runtime技术调研(六)

Objective-C Runtime技术调研(六)

作者: tridonlee | 来源:发表于2017-04-27 22:52 被阅读8次

    一、资料归档篇

    创建TLPeople.h

    #import <Foundation/Foundation.h>

    @interfaceTLPeople :NSObject

    @property(nonatomic,copy)NSString*name;//姓名

    @property(nonatomic,strong)NSNumber*age;//年龄

    @property(nonatomic,copy)NSString*occupation;//职业

    @property(nonatomic,copy)NSString*nationality;//国籍

    @end

    TLPeople.m

    #import"TLPeople.h"

    #if TARGET_IPHONE_SIMULATOR

    #import <objc/objc-runtime.h>

    #else

    #import <objc/runtime.h>

    #import <objc/message.h>

    #endif

    @implementationTLPeople

    -(void)encodeWithCoder:(NSCoder*)aCoder

    {

    unsignedintcount =0;

    Ivar*ivars =class_copyIvarList([TLPeopleclass], &count);

    for(NSUIntegeri =0; i < count; i ++) {

    Ivarivar = ivars[i];

    constchar*name =ivar_getName(ivar);

    NSString*key = [NSStringstringWithUTF8String:name];

    idvalue = [selfvalueForKey:key];

    [aCoderencodeObject:valueforKey:key];

    }

    free(ivars);

    }

    -(instancetype)initWithCoder:(NSCoder*)aDecoder

    {

    self= [superinit];

    if(self) {

    unsignedintcount =0;

    Ivar*ivars =class_copyIvarList([TLPeopleclass], &count);

    for(NSUIntegeri =0; i < count; i ++) {

    Ivarivar = ivars[i];

    constchar*name =ivar_getName(ivar);

    NSString*key = [NSStringstringWithUTF8String:name];

    idvalue = [aDecoderdecodeObjectForKey:key];

    [selfsetValue:valueforKey:key];

    }

    free(ivars);

    }

    returnself;

    }

    @end

    Demo传送门-> 6.1 资料归档篇Demo

    相关文章

      网友评论

        本文标题:Objective-C Runtime技术调研(六)

        本文链接:https://www.haomeiwen.com/subject/xronzttx.html