iOS unarchivedObjectOfClass的使用,即NSData转数组Array

最近在适配iOS12的时候,需要将方法unarchiveObjectWithData替换成unarchivedObjectOfClass:fromData:error:,结果发现返回结果始终为空。

错误示范

+ (nullable id)unarchiveObjectWithData:(id)data
{
    return [NSKeyedUnarchiver unarchivedObjectOfClass:[NSArray class] fromData:data error:nil];
}

正确使用

// NSData转array,转dictionary,转NSString
+ (nullable id)unarchiveObjectWithData:(id)data
{
    NSError *err = nil;
    id item = [NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithArray:@[NSArray.class,NSDictionary.class, NSString.class, UIFont.class, NSMutableArray.class, NSMutableDictionary.class, NSMutableString.class, UIColor.class, NSMutableData.class, NSData.class, NSNull.class, NSValue.class,NSDate.class]] fromData:data error:&err];
    
    return item;
}

如果遇到以下报错:

Error Domain=NSCocoaErrorDomain Code=4864 "value for key 'NS.objects' was of unexpected class 

说明unarchivedObjectOfClasses内的类型不对

你可能感兴趣的:(iOS unarchivedObjectOfClass的使用,即NSData转数组Array)