iphone - 更新主线程上的标签不起作用

标签 iphone ios objective-c uiviewcontroller performselector

我正在尝试在不同的任务进行时更新标签。我搜索并使用了不同的选项并最终使用这种方式,但它仍然不起作用:

[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/

相关文章:

ios - Firebase简单登录错误 "__NSPlaceholderDictionary initWithObjects:forKeys:count:"

ios - 打开位置设置在 iOS 11 中不起作用

ios - UICollectionViewCell 将数据发送到另一个 viewController

iphone - 如何使用 iPhone 应用程序定位任何手机号码

iphone - iPhone SDK上的JSON解析

iphone - Pubnub + React Native - iOS 真实设备上没有横幅通知

ios - 类型 'Character' 的值没有成员 'isUppercase'

iphone - 什么时候设置 Objective-C 属性双重保留?

ios - 尽管用户已终止应用程序并检查 iOS 中的设备位置,如何保持 iOS 应用程序进程始终运行?

iphone - 未调用 GCDAsynSocketDelegate didReadData 方法。使用 GCDAsynSocket