iOS 归档宏

1.归档的宏

#define OBJC_STRINGIFY(x) @#x

#define encodeObject(x) [aCoder encodeObject:x forKey:OBJC_STRINGIFY(x)]

#define decodeObject(x) x = [aDecoder decodeObjectForKey:OBJC_STRINGIFY(x)]

 #define encodeBool(x) [aCoder encodeBool:x forKey:OBJC_STRINGIFY(x)]

#define decodeBool(x) x = [aDecoder decodeBoolForKey:OBJC_STRINGIFY(x)]

 #define encodeInt(x) [aCoder encodeInt:x forKey:OBJC_STRINGIFY(x)]

#define decodeInt(x) x = [aDecoder decodeIntForKey:OBJC_STRINGIFY(x)]

 #define encodeInteger(x) [aCoder encodeInteger:x forKey:OBJC_STRINGIFY(x)]

#define decodeInteger(x) x = [aDecoder decodeIntegerForKey:OBJC_STRINGIFY(x)]

 #define encodeFloat(x) [aCoder encodeFloat:x forKey:OBJC_STRINGIFY(x)]

#define decodeFloat(x) x = [aDecoder decodeFloatForKey:OBJC_STRINGIFY(x)]

#define encodeDouble(x) [aCoder encodeDouble:x forKey:OBJC_STRINGIFY(x)]

#define decodeDouble(x) x = [aDecoder decodeDoubleForKey:OBJC_STRINGIFY(x)]

2.归档的数据类型可以是 int float double integer bool object 和字符串 (字符串 数组 归档都是按对象处理) 

3.如果模型中存在这些属性 

@property (nonatomic,assign) NSInteger filmID;

@property (nonatomic,copy) NSString* race;

4.来到.m文件来实现此方法

- (id)initWithCoder:(NSCoder *)aDecoder

{

    self = [super init];

    if (self)

    {

        decodeInt(_filmID);

        decodeObject(_race);

    }

    return self;

}

- (void)encodeWithCoder:(NSCoder *)aCoder

{

    encodeInt(_filmID);

    encodeObject(_race);

}

5.最好还是有个工具类(ToolsData),直接调用次方法就能取到值 ,在这个工具类中,写两个类方法 

+ (NSDictionary*)medalsDetail;

+ (void)storeMedalDetailData:(NSDictionary*)medals;

6.再次工具类中实现这两个方法

+ (NSDictionary*)medalsDetail

{

    NSData* data = [[NSUserDefaults standardUserDefaults] objectForKey:@"medals_Detail"];

    if (data) {

        return [NSKeyedUnarchiver unarchiveObjectWithData:data];

    }

    return nil;

}

 + (void)storeMedalDetailData:(NSDictionary*)medals

{

    NSData* medalsData = [NSKeyedArchiver archivedDataWithRootObject:medals];

    if (medalsData)

    {

        [[NSUserDefaults standardUserDefaults] setObject:medalsData forKey:@"medals_Detail"];

        [[NSUserDefaults standardUserDefaults] synchronize];

    }

}

综上所述就实现归档

1
原文地址:https://www.cnblogs.com/fantasy3588/p/5312089.html