美文网首页
iOS 【NSKeyedArchier】归档解档类名调整问题

iOS 【NSKeyedArchier】归档解档类名调整问题

作者: NJ_墨 | 来源:发表于2021-11-11 11:19 被阅读0次

    归档解档的是自定义的对象,
    归档时是A名字,当对象名调整之后,解档是B名字;

    *** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (VIVOolbarPal) for key (kArchiverDataKey) because no class named "VIVOolbarPal" was found; the class needs to be defined in source code or linked in from a library (ensure the class is part of the correct target). If the class was renamed, use setClassName:forClass: to add a class translation mapping to NSKeyedUnarchiver'
    terminating with uncaught exception of type NSException

    上面错误提示来源,
    1、NSKeyedArchiver 归档时,对象类名是这个VIVOolbarPal;

    VIVOolbarPal *account = [[VIVOolbarPal alloc] init];
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:account forKey:kArchiverDataKey];
    

    2、运行项目,手机APP上本地归档的是VIVOolbarPal;

    3、VIVOolbarPal 类名调整为新【ABCOolbarPal】类名;

    4、再次运行项目,读取之前APP归档信息报错:

    NSData *data = [[NSData alloc] initWithContentsOfFile:[STL_PATH_DIRECTORY stringByAppendingPathComponent:kUserFileName]];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    ABCVIVOolbarPal *account = [unarchiver decodeObjectForKey:kArchiverDataKey];
    

    '*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (VIVOolbarPal);

    1、简单的方式(获取时,设置之前的类):

    NSData *data = [[NSData alloc] initWithContentsOfFile:[STL_PATH_DIRECTORY stringByAppendingPathComponent:kUserFileName]];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    //设置对应的类
    [unarchiver setClass: ABCVIVOolbarPal.class forClassName:@"VIVOolbarPal"];
    
    ABCVIVOolbarPal *account = [unarchiver decodeObjectForKey:kArchiverDataKey];
    

    2、归档与解档时,都用指定的名字(如ABCCC):

    归档
    VIVOolbarPal *account = [[VIVOolbarPal alloc] init];
    NSMutableData *data = [[NSMutableData alloc] init];
    [NSKeyedArchiver setClassName:@"ABCCC" forClass:account.class];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:account forKey:kArchiverDataKey];
    
    解档
    NSData *data = [[NSData alloc] initWithContentsOfFile:[STL_PATH_DIRECTORY stringByAppendingPathComponent:kUserFileName]];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    //设置对应的类
    //[unarchiver setClass: ABCVIVOolbarPal.class forClassName:@"VIVOolbarPal"];
    [unarchiver setClass: ABCVIVOolbarPal.class forClassName:@"ABCCC"];
    
    ABCVIVOolbarPal *account = [unarchiver decodeObjectForKey:kArchiverDataKey];
    

    相关文章

      网友评论

          本文标题:iOS 【NSKeyedArchier】归档解档类名调整问题

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