NSCoding

存储自定义对象到文件的解决方案

Posted by kunnan on July 20, 2018

前言

  • 解决方案:  只有遵守了NSCoding协议的对象才可以使用NSKeyedArchiver进行归档。

    实现<NSCoding>,并采用NSKeyedUnarchiver、NSKeyedArchiver即可
    

解决方案

采用 JSONModel

  • NSCoding 协议(持久化)的支持 —JSONModel和YYModel都有适配

    JSONMOdel已经实现了一个NSCoping和NSCoding协议,我们可以直接深拷贝和归档
    @interface KNControlInfoModel :  JSONModel <NSCoding>
    

采用封装的宏:  pod ‘MJExtension’

  • //MJExtensionCodingImplementation

code

  • 从文件存储和获取自动对象数据

    + (nullable id)unarchiveObjectWithFile:(NSString *)path{
          
        return [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    }
      
    + (BOOL) archiveRootObject:(id)model path:(NSString*)path{
          
    BOOL isSuccess=  [NSKeyedArchiver archiveRootObject:model toFile:path];// kASsandboxInfopath
    if (isSuccess) {
        NSLog(@"%@",path);
    }
        return isSuccess;
          
    }
      
    

存储字典,其中value为普通类型的变量

  • 存储

        //[config setValue:model.backDocumentspath forKey:[model wxid]];
    
  • 读取

        //NSMutableDictionary* config = [[NSMutableDictionary alloc] initWithContentsOfFile:kASsandboxInfopath];// 因为沙盒的变动的,因此这个路径为相对于沙盒的路径
    

issue

  • 自定义对象,不能存储UIImage 属性

        //7   wxControlTweak.dylib              0x025d0874 +[KNControlInfoModel unarchiveObjectWithFile:] + 22644 (KNControlInfoModel.m:58)
    //    /  Terminating app due to uncaught exception 'NSInvalidArgumentException', reason:  -[NSDictionary initWithObjects:forKeys:]: count of objects (0) differs from count of keys (1)'
    //    3   Foundation                        0x25291530 -[NSDictionary+ 259376 (NSDictionary) initWithCoder:] + 367
      //  4   Foundation                        0x252b1082 _decodeObjectBinary + 3041
        //5   Foundation                        0x252b0390 _decodeObject + 271
        //6   Foundation                        0x25301732 +[NSKeyedUnarchiver unarchiveObjectWithFile:] + 149
    

See Also

/Users/devzkn/bin//knpost NSCoding 存储自定义对象到文件的解决方案 -t objc
#原来""的参数,需要自己加上""

转载请注明: > NSCoding