-1

問題を次のように絞り込みました。

// 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]);

上記のコードは以下を生成します。

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

行をコメントアウトする[imgView setView:nil]と、コードは次のようになります。

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

つまり、基本的[imgView setImage:nil]に保持カウントを 2 増やしますが、1 減らす必要があります。

4

1 に答える 1

3

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.

于 2012-03-18T02:03:33.580 に答える