简体   繁体   English

drawInRect保留NSImage直到将来的某个点?

[英]drawInRect retains NSImage until some point in the future?

So I have some code running in an NSThread that creates, in a loop, a whole bunch of NSImage s. 所以我在NSThread中运行了一些代码,它们在一个循环中创建了一大堆NSImage A small section of each of the images is drawn into another NSImage , and then the thread exits. 每个图像的一小部分被绘制到另一个NSImage ,然后线程退出。

So, something like 所以,像

NSImage *outputImage = [[NSImage alloc] initWithSize:size];
[outputImage lockFocus];
while(1000 times)
    NSImage* image = [[NSImage alloc] initWithSize:size];
    ... image is processed ...
    [image drawInRect: ... fromRect: ... ]
[outputImage unlockFocus];

Once this is complete, the thread uses performSelectorOnMainThread to send the created NSImage back to the main thread to have it placed in a view. 完成后,线程使用performSelectorOnMainThread将创建的NSImage发送回主线程,以将其放置在视图中。

This all works fine, and the final image is exactly as I expect it to be. 这一切都很好,最终的图像完全符合我的预期。 However, during the loop the memory usage of the application rises linearly - as though each NSImage isn't released until some later time. 但是,在循环期间,应用程序的内存使用量呈线性增长 - 就好像每个NSImage直到稍后才释放一样。 My theory is that the drawInRect calls are being pipelined somewhere and not actually executed until later. 我的理论是drawInRect调用在某处被流水线化,直到稍后才真正执行。 Is this correct? 这个对吗? And if so how do I prevent it? 如果是这样,我该如何预防呢? My application will crash if I make my loop counter too large at the moment, and I'd like to avoid that. 如果我现在使我的循环计数器太大,我的应用程序将崩溃,我想避免这种情况。

I've tried moving the locking and unlocking of focus into the loop, but this made no difference. 我已经尝试将锁定和解锁焦点移动到循环中,但这没有任何区别。

I've confirmed that if I take out only the drawInRect call, the memory usage is (more or less) flat for the lifetime of the thread. 我已经确认,如果我只取出drawInRect调用,则线程的生命周期内的内存使用量(或多或少)是平的。 It's only when I put the call in that the memory climbs. 只有在我打电话的时候,内存才会上升。

I'm (obviously?) using ARC in this project, and it's running in OSX10.9. 我(显然是?)在这个项目中使用ARC,它在OSX10.9中运行。

It sounds like your NSImages are being added to the autorelease pool at some point. 听起来你的NSImages在某些时候被添加到自动释放池中。 They won't normally be flushed until the pool is drained. 在池排水之前,它们通常不会被冲洗。

In instances like this you want to make your own autorelease pool: 在这种情况下,您想要创建自己的自动释放池:

NSImage *outputImage = [[NSImage alloc] initWithSize:size];
[outputImage lockFocus];
while(1000 times) {
    @autoreleasepool {
        NSImage* image = [[NSImage alloc] initWithSize:size];
        ... image is processed ...
        [image drawInRect: ... fromRect: ... ]
    }
}
[outputImage unlockFocus];

This creates a sub-pool that will get drained on every pass, so you won't have a huge build-up of images. 这会创建一个子池,每次传递都会耗尽,因此您不会有大量的图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM