传递图像模型数组时,NSKeyedArchiver archivedDataWithRootObject返回nil

时间:2016-07-21 18:25:18

标签: ios objective-c swift nskeyedarchiver

我正在尝试使用[NSKeyedArchiver archivedDataWithRootObject:dataArray]保存包含由图像和字符串组成的模型的数组;但是这个方法在调用这个方法2-3次后返回nil。 这只发生在我尝试存档的模型包含图像时。 我检查过数据数组不是零。 下面是我正在使用的代码:

@implementation ImagesModel

- (id)initWithCoder:(NSCoder *)coder{
    if(self = [super init]){
        self.image = [[UIImage alloc]initWithData:[coder decodeObjectForKey:@"image"]];
        self.urlString = [coder decodeObjectForKey:@"urlString"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder
{
    [coder encodeObject:UIImagePNGRepresentation(self.image) forKey:@"image"];
    [coder encodeObject:self.urlString forKey:@"urlString"];
}

+ (NSDictionary *)getObjectMapper {
    if (!mapperDictionary) {
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        [dictionary setObject:[PropertyMapping mappingForSimpleTypeWithMappedKeyName:@"image"] forKey:@"image"];
        [dictionary setObject:[PropertyMapping mappingForSimpleTypeWithMappedKeyName:@"urlString"] forKey:@"urlString"];
        mapperDictionary = [dictionary copy];
    }
    return mapperDictionary;
}
- (NSData)ArchiveData {
    if (!dataArray){
       return NO;  //nothing to save
     }
 NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dataArray]; //Return Nil
 }

1 个答案:

答案 0 :(得分:0)

这取决于您如何加载图像。 以下是可能对您有帮助的答案:

How to encode a UIImage in an `NSCoder`

另外,如果要存储.JPEG图像,可能需要使用UIImageJPEGRepresentation。