I am trying to save an image on Core Data. The attribute type is "Transformable". When I use the following sentence:
// NOTHING SAVED
entity.image = [UIImage imageNamed:@"a.jpg"];
[self saveContext];
There is nothing saved. But replace the above sentences to 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 am very sure [UIImage imageNamed:@"a.jpg"] returns normally. Anyone knows what happened? Pls.
My Xcode is 6.3
Thank you.
This is very strange behavior. I don't think there's anything that explains this completely, but I'll see what I can do.
The imageNamed: call is different from other ways of creating images in that it makes use of an automatic image cache. When you load an image with imageNamed:, it's automatically cached so it can be re-used quickly. The intended use is for images that are used a lot, such as UI elements. It also works for images you only use once, but there's no real advantage in that case.
So, imageNamed: is doing different stuff internally than other image creation methods. Based on your results (I get the same thing, BTW) this results in an image that works differently, at least some of the time. But when you have a UIImage there doesn't seem to be any way to ask it how it was created or whether it represents a cached image.
I consider this a bug and I recommend reporting it to Apple. In the meantime, you have a workaround. As a safety check it might be a good idea to do something like this, to avoid running into the problem accidentally:
UIImage *image = // loaded in whatever way you want
entity.image = [UIImage imageWithCGImage:image.CGImage];
That step should be unnecessary. But as you've found, sometimes the right way doesn't work.
[In case anyone from Apple sees this: reported as rdar://20717042]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With