Frage

I've narrowed down the problem to this:

// newImage is passed from elsewhere
NSLog(@"retain count first : %lu", [newImage retainCount]);
img = newImage;
[imgView setImage:newImage];
NSLog(@"retain count next : %lu", [newImage retainCount]);
[imgView setImage:nil];
NSLog(@"retain count finally : %lu", [newImage retainCount]);

The above code produces:

2012-03-17 21:51:04.833 App[67425:507] retain count first : 1
2012-03-17 21:51:04.833 App[67425:507] retain count next : 2
2012-03-17 21:51:04.834 App[67425:507] retain count finally : 4

If I comment out the line [imgView setView:nil], the code produces:

2012-03-17 21:51:52.314 App[67479:507] retain count first : 1
2012-03-17 21:51:52.314 App[67479:507] retain count next : 2
2012-03-17 21:51:52.314 App[67479:507] retain count finally : 2

So basically [imgView setImage:nil] increases the retain count by 2, when it should decrease it by 1?!

War es hilfreich?

Lösung

Don't rely on -retainCount. Really, don't. Really.

Probably imgView retained and autoreleased your image. The retain count is higher now, but will be decreased when the autorelease performs its release, after your function returns. (Most likely that will be at the end of the current run loop iteration.)

If you really want to know what's going on, use the Allocations instrument. Turn on "Record reference counts", click through to a specific object, and you can see every memory-management related function that was called on the object (allocation, retain, release, autorelease, and free). It's far more useful than watching retainCount.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top