Save UIImage for Master Data

I am trying to save an image to Core Data. The attribute type is "Transformable". When I use the following suggestion:

// NOTHING SAVED
entity.image = [UIImage imageNamed:@"a.jpg"];
[self saveContext];

      

There is nothing saved. But let's replace the above sentences with the following:

entity.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"a" ofType:@"jpg"]];
[self saveContext];

      

OR

entity.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://some_url/a.jpg"]]];
[self saveContext];

      

OR

entity.image = UIImagePNGRepresentation([UIImage imageNamed:@"a.jpg"]);
[self saveContext];

      

It works!!! So weird. I'm pretty sure that [UIImage imageNamed: @ "a.jpg"] returns fine. Does anyone know what happened? Pls.

My Xcode is 6.3

Thank.

+3


source to share


1 answer


This is very strange behavior. I don't think it fully explains all of this, but I'll see what I can do.

The call imageNamed:

differs from other ways of creating images in that it uses an automatic image cache. When you load an image with imageNamed:

, it is automatically cached so it can be used quickly. The intended use is for images that are used a lot, such as interface elements. It also works with images that you only use once, but there is no real benefit in this case.

So, imageNamed:

does different things internally than other methods of creating images. Based on your results (I get the same thing, BTW) this causes the image to work differently for at least a while. But when you have UIImage

it, there seems to be no way to ask him how it was created or if it represents a cached image.

I believe this is a bug and I recommend reporting it to Apple. In the meantime, you have a workaround. As a security check, it might be a good idea to do something like this to avoid accidental error:



UIImage *image = // loaded in whatever way you want
entity.image = [UIImage imageWithCGImage:image.CGImage];

      

This step shouldn't be superfluous. But, as you found, sometimes the correct path doesn't work.

[In case anyone at Apple sees this: reported as rdar: // 20717042]

+3


source







All Articles