Domanda

I have a drawRect method that is rather slow (100-200ms). To save time, I need to cache the results. I am doing the actual caching like this:

// some code to check if caching would be desirable goes here.  If it is desirable, then
UIGraphicsBeginImageContext(viewSize);
CGContextRef c = UIGraphicsGetCurrentContext();
[view.layer renderInContext: c];
UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
[self.cachedImageArray addObject:image];
UIGraphicsEndImageContext();

The caching itself can take up to 40ms. This is still easily worth it. But the caching has to wait until everything is rendered, or it will come out wrong. Additionally, the caching is a low-priority task. Once everything is displayed, it is possible that other things will still be going on, and if so, the caching can wait. But since it uses UIKit, it has to be on the main thread.

Rather than putting in some arbitrary delay, is there a bulletproof way to wait like this?

È stato utile?

Soluzione

The caching itself doesn't have to be done on the main thread. You can get a copy/reference of the image context or bitmap data, and launch it using an NSThread only when the rendering is done. Example:

- (void) drawRect:(CGRect)rect {
    do_rendering_here();
    // when rendering completed:
    NSThread *t = [[NSThread alloc] initWithTarget:self selector:@selector(doCaching:) object:c];
    [t start];
    [t release];
}

- (void) doCaching:(CGContextRef)ctx {
    // do whatever kind of caching is needed
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top