我正在尝试在不同的任务进行时更新标签。我搜索并使用了不同的选项并最终使用这种方式,但它仍然不起作用:
[processStatusLable performSelectorOnMainThread:@selector(setText:) withObject:@"Creating your account..." waitUntilDone:NO];
DCConnector *dccon = [DCConnector new];
ContactsConnector *conCon = [ContactsConnector new];
if (![dccon existUsersData]) {
[dccon saveUsersInformation:device :usDTO];
//created account
//get friends -> Server call
[processStatusLable performSelectorOnMainThread:@selector(setText:) withObject:@"Checking for friends..." waitUntilDone:NO];
NSMutableArray *array = [conCon getAllContactsOnPhone];
// save friends
[processStatusLable performSelectorOnMainThread:@selector(setText:) withObject:@"Saving friends.." waitUntilDone:NO];
if ([dccon saveContacts:array]) {
[processStatusLable performSelectorOnMainThread:@selector(setText:) withObject:@"Friends saved successfully.." waitUntilDone:NO];
}
}
最后一个 performSelector
正在执行(至少我看到 View 上的标签文本发生了变化),但所有其他选择器都不起作用。知道为什么吗?
编辑 1
- (void)updateLabelText:(NSString *)newText {
processStatusLable.text = newText;
}
最佳答案
我们可以使用下面的代码在主线程上运行一些东西,
dispatch_async(dispatch_get_main_queue(), ^{
//set text label
});
使用它我们可以编写这样的方法,
- (void)updateLabelText:(NSString *)newText {
dispatch_async(dispatch_get_main_queue(), ^{
processStatusLable.text = newText;
});
}
最后,您可以使用这种方式更改您的代码,
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self updateLabelText:@"Creating your account..."];
DCConnector *dccon = [DCConnector new];
ContactsConnector *conCon = [ContactsConnector new];
if (![dccon existUsersData]) {
[dccon saveUsersInformation:device :usDTO];
//created account
//get friends -> Server call
[self updateLabelText:@"Checking for friends..."];
NSMutableArray *array = [conCon getAllContactsOnPhone];
// save friends
[self updateLabelText:@"Saving friends.."];
if ([dccon saveContacts:array]) {
[self updateLabelText:@"Friends saved successfully.."];
}
}
});
关于iphone - 更新主线程上的标签不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16320969/