Arbel Israeli Arbel Israeli - 1 month ago 16
Swift Question

Can you save an array of images in core data?

I know you can save one by using the binary data property of an entity but is it possible to save multiple?

you can save one by using this:

UIImageJPEGRepresentation(image: UIImage)


you can save it and then transform it into an image again with

UIImage(data: ____)


but can I transform an array full of images into binary data?

If you can't with core data, any other ways I can do it?

BTW, the image array is full of user taken image saved on the device..

Thanks for all the helpers!

Answer

convert your array to NSMutableArray and archive it as NSData

var imgArray = [UIImage]();

var CDataArray = NSMutableArray();

for img in imgArray{
    let data : NSData = NSData(data: UIImagePNGRepresentation(img))
    CDataArray.addObject(data);
}

//convert the Array to NSData
//you can save this in core data
var coreDataObject = NSKeyedArchiver.archivedDataWithRootObject(CDataArray);

after pulling from CData, extract data:

//extract:
if let mySavedData = NSKeyedUnarchiver.unarchiveObjectWithData(coreDataObject) as? NSArray{
    //extract data..
}
Comments