iOSデータの永続化:アーカイブ解除

2794 ワード

ターゲット:modelクラススキームなどのカスタムオブジェクトを砂箱に格納します.アーカイブを使用するか、コードを直接アップロードするか、説明的な文字が弱いです.
1.アーカイブを使用するには、プロトコルを遵守する必要がある.ここでage属性をNSNumberタイプとして宣言する理由は、主に後のruntimeのためである.h
#import 

@interface PYHModel : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSNumber *age;
@property (nonatomic, strong) NSNumber *sex;
@property (nonatomic, copy) NSString *address;

- (instancetype)initWithDict:(NSDictionary *)dict;
@end

2.プロトコルを実現する方法ここで私はruntimeを使って怠け者を盗んですべての属性を書かなくてもいいです.m
- (NSArray *)allPropertyKey {
    if (!_allPropertyKey) {
        NSMutableArray *pps = [NSMutableArray array];
        
        //               
        unsigned int outCount = 0;
        objc_property_t *models = class_copyPropertyList([self class], &outCount);//      
        for (unsigned int i = 0; i < outCount; i ++) {
            objc_property_t model = models[i];//        
            NSString *propertyKey = [NSString stringWithUTF8String:property_getName(model)];
            [pps addObject:propertyKey];
        }
        free(models);
        
        _allPropertyKey = pps.copy;
    }
    return _allPropertyKey;
}

//  
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        [self.allPropertyKey enumerateObjectsUsingBlock:^(NSString * _Nonnull propertyKey, NSUInteger idx, BOOL * _Nonnull stop) {
            id propertyValue = [aDecoder decodeObjectForKey:propertyKey];
            [self setValue:propertyValue forKey:propertyKey];
        }];
    }
    return self;
}

//  
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [self.allPropertyKey enumerateObjectsUsingBlock:^(NSString * _Nonnull propertyKey, NSUInteger idx, BOOL * _Nonnull stop) {
        id propertyValue =  [self valueForKey:propertyKey];
        [aCoder encodeObject:propertyValue forKey:propertyKey];
    }];
}

3.当然、アーカイブを行うにもapiを呼び出す必要がある
//             
PYHModel *model = [[PYHModel alloc]initWithDict:@{@"name":@"pyh",@"address":@"hangzhoubingjiang",@"age":@28,@"sex":@"1"}];
BOOL result = [NSKeyedArchiver archiveRootObject:model toFile:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"model"]];
NSLog(@"%@",result ? @"    " : @"    ");

//                
PYHModel *model = [NSKeyedUnarchiver unarchiveObjectWithFile:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"model"]];
NSLog(@"%@",model);

このアーカイブの使用は終了しましたdemo:https://github.com/DeepSeaGhost/archiver