2016-10-20 7 views
3

私はObjective Cを初めて使っていますが、今すぐSwiftに取り組んでいます。私はObjective cを論理的にswiftと似ていると仮定しました。私は、jsonのデータ要求を処理している間に警報コントローラを提示する必要があります。だから私は迅速に動作するようにディスパッチ非同期を使用しなければならなかった。ここで私はスウィフトで使用されるコードです:ディスパッチ非同期コードエラー - 目的C

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) 
    }) 
} 

は、しかし、私はそう

- (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]; 
})]; 
} 

私は「識別子を期待される」エラーを取得していますように客観Cで同じことを実行しようとしました。私は間違って何をしていますか?

+0

[自己presentViewController:アラートのアニメーション:真完了:nilを];これが問題を引き起こしている可能性があります。NULLをnilに置き換えます。 –

+0

エラーが発生している行はありますか? – Arun

+0

@Arunの2行目の最後の行}}]; ] –

答えて

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]; 
    }); 

} 
+0

はい。これはうまくいった。ありがとう。 –

+4

その理由: 'dispatch_async()'は** C関数**です。角括弧 '[]'は** Objective-cメソッド**を囲みます。 –

4

"dispatch_async"は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(), ^{ 
     [self presentViewController:alert animated:true completion:nil]; 
    }); 
} 
2

試すことができ、今

- (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:nil]; 
    }); 
} 

出力:

enter image description here

..コーディングハッピー

関連する問題