我有使用-(void)drawRect:(CGRect)rect
函数绘制的图形视图,它是一个复杂的图形,包括日期为X轴,时间为Y轴。因此,每次绘制时,显示最终图形总是需要2,3秒。红点可能是红色,绿色或黄色,其颜色取决于从数据库中读取的数据。
我的问题是如何使用多线程或以快速方式绘制此视图。 例如,在一个线程中绘制X轴和Y轴,并在分离的线程中绘制每一天的图形(使用30个线程)或在分离的线程中绘制每个小时30天的图形(使用5个线程)? 我尝试使用以下功能:
for(int i = 0; i < 31; i++){
NSString *threadStr = [NSString stringWithFormat:@"%i", i];
dispatch_queue_t queue1 = dispatch_queue_create([threadStr UTF8String], NULL);
dispatch_async(queue1, ^{
//Draw my graphics for one day
.....
});
}
但有时这些线程同时读取数据库,其中一些线程无法正确获取数据,这导致最终图形不完整。 有人能给我一些建议吗? 非常感谢你。
如果我使用主线程绘制它,我试图找出它延迟2,3秒的原因。 是因为阅读 SQLite3 数据库吗?
绘制此图形的过程是:
- (void)drawRect:(CGRect)rect
{
1.draw X axis with date label;
2.draw Y axis with time label;
NSArray *timeArray = @[@"08:00", 11:00", 14:00", 17:00", 20:00"];
for(NSString *timeStr in timeArray){
for(int i = 0; i < 31; i++){
NSString *DateTimeStr = dateStr + timeStr;
int a = [DataManager getResult: DateTimeStr];
UIColor *RoundColor;
if(a == 1){
RoundColor = [UIColor colorWithRed:229/255.0 green:0/255.0 blue:145/255.0 alpha:1.0];
}
else if(a == 2){
RoundColor = [UIColor colorWithRed:0/255.0 green:164/255.0 blue:229/255.0 alpha:1.0];
}
else if(a == 3){
RoundColor = [UIColor colorWithRed:229/255.0 green:221/255.0 blue:0/255.0 alpha:colorAlpha];;
}
const CGFloat *components = CGColorGetComponents(RoundColor.CGColor);
CGContextSetRGBFillColor(context, components[0], components[1], components[2], components[3]);
CGContextFillEllipseInRect(context, CGRectMake(roundXnow,roundYnow,roundR,roundR));
}
}
}
我在想,如果在阅读 SQLite3 数据库时出现延迟,因为我知道我的数据库中有很多记录。
答案 0 :(得分:1)
这里绘制的操作非常简单,很可能您遇到的时间问题与计算(或获取数据)或实际绘制点之前您正在做的其他事情有关。所以特别要使用仪器,时间分析器。它将向您显示哪些操作需要更长时间(查看应用程序运行时将显示的图形中的长矛)。 这将为您提供线索。
除了在这里正确提到之外,所有的UI都应该在主线程中执行。 但是,您可能对数据进行了预先计算和提取 - 如果可能的话,您应该在哪里寻找多线程解决方案。