我怎么可能获得 100% 的 CPU 并阻塞后台队列中的主线程。我这样做:
首先,我在自定义设置器中创建上下文:
-(void)setContext:(NSManagedObjectContext *)context {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
_context = context;
});
}
然后我使用下载一些数据NSURLConnectionDataDelegate
,然后是我的插入方法:
-(void)connectionDidFinishWithObject:(NSArray*)arrayOfObjects {
dispatch_queue_t fetchQ = dispatch_queue_create("myDispatch", NULL);
dispatch_async(fetchQ, ^{
[self.context performBlock:^{
for(NSDictionary *dic in myArr) {
[Tournament tournamentWithDictionary:dic inMOC:self.context];
}
}];
}
}
这是我对子NSManagedObject
类的插入:
+(Tournament*)tournamentWithDictionary:(NSDictionary*)dictionary inMOC:(NSManagedObjectContext*)moc {
Tournament *finalElement;
if(!finalElement) {
finalElement = [NSEntityDescription insertNewObjectForEntityForName:@"Tournament" inManagedObjectContext:moc];
[finalElement setTournamentID:[NSNumber numberWithInt:[[dictionary objectForKey:@"ID"] integerValue]]];
}
return finalElement;
}
而且我的 CPU 使用率达到 100%,而且我的界面被阻塞了!为什么?!