在主线程上调用方法? [英] Calling a method on the main thread?

查看:133
本文介绍了在主线程上调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我正在为iphone编写代码。
我需要能够在主线程上调用方法而不使用 performSelectorOnMainThread
我不想使用 performSelectorOnMainThread 的原因是当我尝试为单元测试创​​建模拟时它会导致问题。

First of all I am writing code for iphone. I need to be able to call a method on the main thread without using performSelectorOnMainThread. The reason that I don't want to use performSelectorOnMainThread is that it causes problem when I am trying to create a mock for unit testing.

[self performSelectorOnMainThread:@Selector(doSomething) withObject:nil];

问题是我的模拟知道如何调用 doSomething 但它不知道如何调用 performSelectorOnMainThread

The problem is that my mock knows how to call doSomething but it doesn't know how to call performSelectorOnMainThread.

那么任何解决方案?

推荐答案

目标C

dispatch_async(dispatch_get_main_queue(), ^{
  [self doSomething];
});

Swift

dispatch_async(dispatch_get_main_queue()) {
   self.doSomething()
}

Swift 3& Swift 4

Swift 3 & Swift 4

DispatchQueue.main.async{
   self.doSomething()
}

这篇关于在主线程上调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆