iOS 利用归档解档实现类似微博及一些CRM类软件的草稿箱思路

来源:互联网 发布:程序员漫画 编辑:程序博客网 时间:2024/04/16 18:27

实际上就是写一个model类 然后将要存数据放到model中,然后将model添加到数组,然后对数组及数组中放的model归档,本地存储起来,解档,拿到数据在需要的地方显示出来


因为model是一个自己写的类 方便起见 归档解档encodeWithCoder和initWithCoder:方法中用了runtime获取属性

下面是核心代码(由于刚开始只是存当前登录用户的数据所以存的是一个数组,后来想到切换用户,然后将数组按登录用户的userid存到字典中然后再存储的,所以代码中有些字典标识符写得不够准确名称中含有array)

model 的相关代码

////  LMDraftModel.h//  TestArchiver////  Created by 闵哲 on 2017/6/13.//  Copyright © 2017年 Gunmm. All rights reserved.//#import <Foundation/Foundation.h>@interface GunmmDraftModel : NSObject/* 数据 */@property (nonatomic, strong) NSDictionary *dataDic;/* 时间 */@property(nonatomic,copy)NSString *time;/* 类型 */@property(nonatomic,copy)NSString *entityName;@end

////  LMDraftModel.m//  TestArchiver////  Created by 闵哲 on 2017/6/13.//  Copyright © 2017年 Gunmm. All rights reserved.//#import "GunmmDraftModel.h"#import <objc/runtime.h>@interface GunmmDraftModel()<NSCoding>@end@implementation GunmmDraftModel-(void)encodeWithCoder:(NSCoder *)aCoder{    unsigned int outCount = 0;    Ivar *ivars = class_copyIvarList([self class], &outCount);    for (unsigned int i = 0; i<outCount; i++) {        Ivar ivar = ivars[i];        NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];        id value = [self valueForKey:key];        [aCoder encodeObject:value forKey:key];    }    free(ivars);}-(instancetype)initWithCoder:(NSCoder *)aDecoder{    self = [super init];    if (self) {        unsigned int OutCount = 0;        Ivar *ivars = class_copyIvarList([self class], &OutCount);        for (unsigned int i=0; i<OutCount; i++) {            Ivar ivar = ivars[i];            NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];            [self setValue:[aDecoder decodeObjectForKey:key] forKey:key];        }        free(ivars);    }    return self;}@end

存储的管理类的相关代码

////  KeyArchiverManager.h//  TestArchiver////  Created by 闵哲 on 2017/6/13.//  Copyright © 2017年 Gunmm. All rights reserved.//#import <Foundation/Foundation.h>@interface KeyArchiverManager : NSObject/** *  单例 * *  @return 返回单例对象 */+ (instancetype)sharedClient;/** *  对数据进行归档 * *  @param dataArray 需要进行归档的数据 */-(void)setArchiverDataWithData:(NSMutableDictionary *)dataDic;/** *  获取解归档的数据 * *  @return 解归档后的数组 */- (NSMutableDictionary *)getArchiverData;/** *  获取文件路径 * *  @return 返回文件路径 */-(NSString *)getAllFilePath;@end


////  KeyArchiverManager.m//  TestArchiver////  Created by 闵哲 on 2017/6/13.//  Copyright © 2017年 Gunmm. All rights reserved.//#import "KeyArchiverManager.h"/** *  文件后缀名 */NSString *const kFileDefaultPathExtension = @"cache";/** *  默认文件名 */NSString *kFileDefaultFileName = @"draftFile";@implementation KeyArchiverManager/** *  单例 * *  @return 返回单例对象 */+ (instancetype)sharedClient{    static KeyArchiverManager *client = nil;    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        client = [[KeyArchiverManager alloc]init];    });    return client;}/** *  对数据进行归档 * *  @param dataArray 需要进行归档的数据 */-(void)setArchiverDataWithData:(NSMutableDictionary *)dataDic{    NSString *fileAllPath = [self getAllFilePath];    if([[NSFileManager defaultManager] fileExistsAtPath:fileAllPath]) {//先将该地址存在的文件删除,再存储。        NSError *error    = nil;        if(![[NSFileManager defaultManager] removeItemAtPath:fileAllPath error:&error]) {            NSLog(@"Cannot remove file: %@", error);        }    }    [NSKeyedArchiver archiveRootObject:dataDic toFile:fileAllPath];}/** *  获取解归档的数据 * *  @return 解归档后的数组 */- (NSMutableDictionary *)getArchiverData{    NSString *fileAllPath = [self getAllFilePath];    NSMutableDictionary *newDataArray = [NSKeyedUnarchiver unarchiveObjectWithFile:fileAllPath];    return newDataArray;}/** *  获取文件路径 * *  @return 返回文件路径 */-(NSString *)getAllFilePath{    NSString *paths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];    NSString *fileAllPath = [[paths stringByAppendingPathComponent:kFileDefaultFileName] stringByAppendingPathExtension:kFileDefaultPathExtension];    return fileAllPath;}@end
简单使用

-(void)saveDraftBox{    //model    GunmmDraftModel *model = [[GunmmDraftModel alloc]init];    model.dataDic = _draftDictionary;    model.entityName = @"event";    NSDateFormatter* formater = [[NSDateFormatter alloc] init];    [formater setDateFormat:@"yyyy-MM-dd HH:mm:SS"];    NSString *time = [formater stringFromDate:[[NSDate alloc]init]];    model.time = time;            NSMutableDictionary *draftDictionary = [[KeyArchiverManager sharedClient]getArchiverData];    if (!draftDictionary) {        draftDictionary = [NSMutableDictionary dictionary];    }        NSMutableArray *draftArrays = [[draftDictionary objectForKey:[WiseApplicationViewController getUserId]]mutableCopy];    if (!draftArrays) {        draftArrays = [NSMutableArray array];    }        if ([_pageType isEqualToString:@"draftPage"]) {        [draftArrays replaceObjectAtIndex:_indexOfKeyArchiver withObject:model];    }else if ([_pageType isEqualToString:@"newPage"]){        [draftArrays insertObject:model atIndex:0];    }        [draftDictionary setObject:draftArrays forKey:[WiseApplicationViewController getUserId]];    [[KeyArchiverManager sharedClient]setArchiverDataWithData:draftDictionary];    }

 NSDictionary *dataDic = [[KeyArchiverManager sharedClient]getArchiverData];    dataList = [dataDic objectForKey:[WiseApplicationViewController getUserId]];






原创粉丝点击