开发者

How does NSImage's data retaining behaviour work?

I have a method that constantly loads new image data from the web. Whenever all data for an image has arrived, it is forwarded to a delegate like this:

NSImage *img = [[NSImage alloc] initWithData:dataDownloadedFromWeb];
if([[self delegate] respondsToSelector:@selector(imageArrived开发者_运维技巧:)]) {
    [[self delegate] imageArrived:img];
} 
[img release]; 

In imageArrived: the image data is assigned to an NSImageView:

- (void)imageArrived:(NSImage *)img
{
    [imageView1 setImage:img];
}

This works nicely, the image is being displayed and updated with every new download cycle. I have profiled my application with Instruments to ensure that there is no leaking - it doesn't show any leaking. However, if I check with Instruments' Activity Monitor, I can see my application grabbing more and more memory with time, roughly increasing by the size of the downloaded images. If I omit [imageView1 setImage:img], memory usage stays constant. My question is: how is that happening? Is my code leaking? How does the NSImage instance within NSImageView determine when to release its data? Thanks for your answers!


When you do initWithData, the retain count on the data is incremented by one. Releasing the image does not change the retain count on the data. That's where your memory is going. The image structures are coming and going the way you want, but the data chunks are accumulating.

save the data handle separately and clean that out after disposing of the nsimage, and all should be well:

(id) olddata = 0; // global or something with persistence
your_routine
{
    (id) newdata = dataDownloadedFromWeb;
    NSImage *img = [[NSImage alloc] initWithData: newdata];
    if([[self delegate] respondsToSelector:@selector(imageArrived:)])
    {
        [[self delegate] imageArrived:img];
    }
    [img release];
    if (olddata) [olddata release];
    olddata = newdata;
}

cleanup
{
    if (olddata) [olddata release];
    olddata = 0;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜