如何同时执行两个UI更新?

Ran*_*all 6 iphone xcode multithreading ios

从我通过阅读Apple的文档可以看出,UI更新只能在主线程上运行.

我的应用程序在屏幕的上半部分进行了一些渲染,并在下半部分有一个表格视图.如果用户在上半部分重新绘制时滚动表格,则表格会锁定半秒钟左右.有什么方法可以改善这种情况吗?

ugh*_*fhw 1

如果绘制视图需要花费大量时间,我建议在更新时将其绘制到后台线程中的图像中,并让视图简单地绘制图像。这将防止主线程阻塞很长时间。

以下代码演示如何从后台线程创建位图上下文并将其绘制到位图上下文中。当您调用该updateInBackground方法时,它将创建一个新的后台线程,该线程创建并绘制到上下文中,然后使用该上下文创建图像。如果将其放入 的自定义子类中UIImageView,则图像将自动绘制到屏幕上。

- (void)updateInBackground {
    [self performSelectorInBackground:@selector(_drawInBackground:) withObject:[NSValue valueWithCGRect:self.bounds]];
}
- (void)_drawInBackground:(NSValue *)boundsValue {
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    CGRect bounds = [boundsValue CGRectValue];
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    if(!colorSpace) {
        [pool drain];
        return;
    }
    CGContextRef context = CGBitmapContextCreate(NULL,bounds.size.width, bounds.size.height, 8, bounds.size.width * 32, colorSpace, kCGImageAlphaPremultipliedFirst);
    CGColorSpaceRelease(colorSpace);
    if(!context) {
        [pool drain];
        return;
    }
    CGContextConcatCTM(context, CGAffineTransformMake(1,0,0,-1,0,bounds.size.height));

    // do drawing here

    CGImageRef image = CGBitmapContextCreateImage(context);
    [self performSelectorOnMainThread:@selector(setImage:) withObject:[UIImage imageWithCGImage:image] waitUntilDone:YES];
    CGImageRelease(image);
    CGContextRelease(context);
    [pool drain];
}
Run Code Online (Sandbox Code Playgroud)

在后台线程中绘图时,不能使用 UIKit 对象和方法。所有绘图必须使用Quartz 函数完成。如果您需要使用 UIKit,后台线程可以调用主线程上的方法来完成绘图的该部分:

[self performSelectorOnMainThread:@selector(drawInMainThread:) withObject:[NSValue valueWithPointer:context] waitUntilDone:YES];

- (void)drawInMainThread:(NSValue *)value {
    UIGraphicsPushContext((CGContextRef)[value pointerValue]);
    // do drawing using UIKit
    UIGraphicsPopContext();
}
Run Code Online (Sandbox Code Playgroud)