0

On one hand, I'm just curious.

On the other, I have to count somehow the amount of images created (to trigger cleanup at some quantity). Unfortunately memory warnings notify me too late, the app gets terminated before I have any chance to react, so thatswhy I want to work this issue around.

I could scatter around my project with a global counter, that increments before I make any UIImage operation, but obviously this is exactly what I want to avoid, that would result in an unmaintainable design.

So I was thinking about subclass UIImage initializers (some kind of MYImage class), than use MYImage troughout the project, but UIImageView's would use UIImages anyway (maybe I can set UIImageView's setImage method, but I bet UIKit uses actual _image instance variable at many cases).

The best would be to count pixels amount from UIImage sizes, so I could flush image memory above a given pixelcount.

Any notification? Something trough categories? Or some kind of NSObject KVO observing (with literal checkings on class/method names)? Do you have ideas/experiences?

Geri Borbás
  • 15,810
  • 18
  • 109
  • 172

1 Answers1

1

There a a lot of ways you could accomplish this. One way would be to override one (or more) of the image creation methods in a subclass, get the size of the image created, and add that to a user default to keep track of the cumulative sizes of all the images. For example, I overrode imageNamed like this:

@implementation RDImage

+(UIImage *)imageNamed:(NSString *) name {
    UIImage *anImage = [super imageNamed:name];
    double oldSize = [[NSUserDefaults standardUserDefaults] doubleForKey:@"SizeAsWxH"];
    [[NSUserDefaults standardUserDefaults] setDouble:(anImage.size.width * anImage.size.height) + oldSize forKey:@"SizeAsWxH"];
    if ([[NSUserDefaults standardUserDefaults] doubleForKey:@"SizeAsWxH"] > 6912) {
        NSLog(@"Too big -- do something");
    }
    return anImage;
}

In the applicationDidFinishLaunchingWithOptions: method, I set the value of that key to zero.

In the view controller when I create an image, I just use my class to make a new one:

UIImage *anImage = [RDImage imageNamed:....

Another way would be to override the setImage: method of UIImageView, and do the same kind of thing inside that method.

rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • My only fear is that I have no idea about the implementation of UIImageView (and I should not have any idea), so this implementation is assuming that UIImageView is setting its image trought its setter, and not directly assign to the pointer. – Geri Borbás Sep 27 '12 at 10:48