调度异步代码错误 - 目标C.

Aji*_* O. 3 objective-c ios

我是Objective C的新手,但现在已经在Swift上工作了一段时间.我假设Objective c在逻辑上类似于swift.我在处理json数据请求时必须提供警报控制器; 所以我不得不使用dispatch async让它在swift中工作.这是我在Swift中使用的代码:

    func alertMessage(message : String) -> Void {
    let alert = UIAlertController(title: "Alert", message: message, preferredStyle: .Alert)
    let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
    alert.addAction(okAction)
    dispatch_async(dispatch_get_main_queue(),{
        self.presentViewController(alert, animated: true, completion: nil)
    })
}
Run Code Online (Sandbox Code Playgroud)

但我试图在目标C中做同样的事情

- (void)alertMessage : (NSString*) message {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Alert" message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:NULL];
[alert addAction:okAction];
[dispatch_async(dispatch_get_main_queue(), ^(void){
    [self presentViewController:alert animated:true completion:NULL];
})];
}
Run Code Online (Sandbox Code Playgroud)

我收到错误"预期标识符".我究竟做错了什么?

Dar*_*ana 6

它只是语法错误.试试以下

- (void)alertMessage : (NSString*) message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Alert" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:NULL];
    [alert addAction:okAction];

    dispatch_async(dispatch_get_main_queue(), ^(void){
        [self presentViewController:alert animated:true completion:NULL];
    });

}
Run Code Online (Sandbox Code Playgroud)

  • 原因是:`dispatch_async()`是一个**C函数**.方括号`[]`括起来**Objective-c方法**. (4认同)