我有一个将数据远程加载到核心数据的ipad应用程序,我不断地向标签显示状态更新,但看起来我的方法中的所有内容都必须在将消息发送到UILabel之前完成。
我该如何解决这个问题?
示例代码:
-(void) importCollections {
/* code left out for brevity */
for (int j=0; j <[[myCollections objectAtIndex:i] count]; j++)
{
Collection *entity = (Collection*) [NSEntityDescription insertNewObjectForEntityForName:@"Collection" inManagedObjectContext:managedObjectContext];
[entity setCollectionName:[[[myCollections objectAtIndex:i] objectAtIndex:j] valueForKey:@"CollectionName"]];
[entity setCollectionID:[[[myCollections objectAtIndex:i] objectAtIndex:j] valueForKey:@"CollectionID"]];
[entity setManufacturer:[manufacturers objectAtIndex:i]];
NSError *error;
if (![managedObjectContext save:&error]) {
// Handle the error.
NSLog(@"%@",error);
}
importStatus.text =[NSString stringWithFormat:@"importing collection: %@", entity.CollectionName];
}
}
在上面的代码中,importStatus是我需要不断更新的UILabel,但它似乎要等到这个方法中的所有内容都完成后才开始。
答案 0 :(得分:1)
你可能从主线程中调用importCollections
。这样,只要您阻止主线程并且不返回运行循环,就不会给UIKit更新UI。
您应该在后台线程上进行冗长的计算或加载资源。因为您只能从主线程更新UI元素,所以必须将您的UIKit调用包装到performSelectorOnMainThread:withObject:waitUntilDone:
。