How to store an image in core data

You can store images in Core Data using the Binary Data attribute type.
However you should be aware of a few things:

  • Always convert your UIImage to a portable data format like png or jpg
    For example:

    NSData *imageData = UIImagePNGRepresentation(image);

  • Enable “Allows external storage” on this attribute
    description
    Core Data will move the data to an external file if it hits a certain threshold. This file is also completely managed by Core Data, so you don’t have to worry about it.

  • If you run into performance issues, try moving the Binary Data attribute to a separate entity.

  • You should abstract the conversion to NSData behind the interface of your NSManagedObject subclass, so you don’t have to worry about conversions from UIImage to NSData or vice versa.

  • If your images are not strongly related to the entities in your model, I would suggest storing them outside of Core Data.

Leave a Comment