2

I am trying to save an array containing models which consist of an image and a string using [NSKeyedArchiver archivedDataWithRootObject:dataArray]; but this method returns nil after 2-3 times of calling this method . This only happens when the model I am trying to archive contains image. I have checked that data array is not nil. Beneath is code I am using :

@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 Answers1

0

It depends on how you have loaded your image. Here is an answer that might help you:

How to encode a UIImage in an `NSCoder`

Also, you might want to use UIImageJPEGRepresentation if you want to store .JPEG images.

Community
  • 1
  • 1
fiks
  • 1,045
  • 9
  • 21