开发者

CGImage, NSArray and Memory

This is a multiple part question, mostly because my ignorance on the matter has multiple layers.

First, I put together a caching system for caching CGImageRef objects. I keep it at the CGImageRef level (rather than UIImage) as I am loading images in background threads. When an image is loaded I put it into a NSMutableDictionary. I had to do a bit of arm twisting to get CGImageRef's into the array:

//Bunch of stuff drawing into a context
CGImageRef imageRef = CGBitmapContextCreateImage(context);

CGContextRelease(context); 
[(id)imageRef autorelease];
[self.cache setObject:(id)imageRef forKey:@"SomeKey"];

So, as you can see, I'm trying to treat the Image Ref as an NSObject, setting it to autorelease then placing it in the dictionary. My expectation is this will allow the image to be cleaned up after being removed from the dictionary. Now, I am beginning to have my doubts.

My application clears the cache array when the user "restarts" to play with different images. Running the application in Instruments shows that the memory is not dropping back to the "start" level on restart, but instead remains steady. My gut tells me that when the array has all objects removed the CGImageRef is not being cleared.

However, I'm unable to confirm this as I don't quite know how to track down the actual source of the memory in instruments. It's just a list of (Malloc 16 Bytes, Malloc 32 Bytes, etc), drilling into them just show a list of dyld callers. Not sure how to properly read it.

So, first question, is my way of caching CGImageRef objects completely flawed? And is there a better way to confirm开发者_运维技巧 such things in instruments?


First of all, caching CGImages is OK and I don't see any problems with the code you posted.

Am I correctly assuming you use an NSMutableDictionary as the cache? If so, you can clear it by sending it -removeAllObjects, which should release all the keys and values. If you just set different images for the same keys, memory usage may remain roughly the same because you replace previous images with new ones. If the images have the same size, memory usage should be constant except brief spikes when you create a new batch of images.

As for Instruments, I've seen it both report false positives and miss real leaks. Try running it several times, making pauses, if possible, for the Leaks instrument to "catch up". This sounds crazy, but I think it may make it a bit more reliable.

If all else fails, you can log the contents of the cache before and after loading a set of images to make sure the cache itself works as expected.


Why not just cache UIImage objects; you can make them fine on a background thread?

It's UIImageView objects that you have to be more careful with and even they are OK for most operations in the background.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜