How to store an image in Core Data?

后端 未结 3 1964
暖寄归人
暖寄归人 2021-02-03 14:52

Just a guess: I make an attribute and make it\'s type \"binary\". But in the end, how would I use that? I guess there is an NSData behind the scenes? So that attribute actually

3条回答
  •  借酒劲吻你
    2021-02-03 15:30

    Marcus's answer works, but it's not the easy way - and, AFAICT, it's not how Apple "intends" you to do it. In theory, you should be able to just mark the image as "Transformable", and CD would do everything automatically.

    That doesn't work because UIImage is "missing" the implementation of NSCoding - Apple's serialization system - and so the default transformer from CD has no idea how to save an image.

    The alternative, which requires a little code, but is still simpler than Marcus's approach ... allegedly you run into Apple's bugs. Apple's CoreData implementation (allegedly) has been broken since 2008 - the custom transformers are ignored for any data-store of type "Binary".

    Going back to "CD would do everything automatically, if only UIImage were setup right" ... IMHO, UIImage ought to be serializable, even if the "Default" serialization isn't ideal for all cases. If you fix that, then lo and behold ... CoreData starts saving/laoding UIImage instances with zero coding from you.

    Here's code to make your UIImage instances all serializable. All you have to do is import this category / copy paste this category into the classes where you want the "upgraded" UIImage version.

    @implementation UIImage (MyCategory)
    
    - (void)encodeWithCoder:(NSCoder *)encoder
    {
        [encoder encodeDataObject:UIImagePNGRepresentation(self)];
    }
    
    - (id)initWithCoder:(NSCoder *)decoder
    {
        NSData *data = [[decoder decodeDataObject] retain];
    
        return [[UIImage alloc] initWithData:data];
    }
    
    @end
    

提交回复
热议问题