我在Cocoa Touch Framework
中创建了swift
(称为MyFramework)。在MyFramework中,我有需要函数作为参数的方法。简而言之,MyFramework包含以下代码:
public class MyFramework : NSObject {
public func MyMethod(successCallback : (String) -> Void, errorCallback : (String, String) -> Void) -> Void {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// successCallback("some value");
// errorCallback("error reason", "error message");
});
}
}
我可以在称为
MyFramework
的Single View Application
中包含MyAppSwift
(在swift
中),并通过以下代码成功调用ViewController.swift
中的MyFramework的MyMethod:class ViewController: UIViewController {
let myframework : MyFramework = MyFramework();
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
myframework.MyMethod(self.onSuccess, errorCallback : self.onError);
}
private func onSuccess(value : String) {
// ...
}
private func onError(reason : String, error : String) {
// ...
}
}
我可以在称为
MyFramework
的Single View Application
中包含MyAppObjectiveC
(在Objective-c中),但是我不知道如何在MyMethod
中调用MyFramework的ViewController.m
...// In ViewController.h
#import <UIKit/UIKit.h>
#import <MyFramework/MyFramework.h>
@interface ViewController : UIViewController {
}
@property (strong, nonatomic) MyFramework * myframework;
- (void) onSuccess : (NSString *) value;
- (void) onError : (NSString *) reason : (NSString *) error;
@end
。
// In ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void) viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.myframework = [[MyFramework alloc] init];
[self.myframework MyMethod : self onSuccess, self onError];
}
- (void) onSuccess : (NSString *) value {
// ...
}
- (void) onError : (NSString *) reason : (NSString *) error {
// ...
}
@end
这行[self.myframework MyMethod:self onSuccess,self onError];不管用。 Xcode在onSuccess之后说期望标识符“:”,然后期望表达式。我不确定要插入什么。我读了关于stackoverflow的几个答案,如何在Objective-C中将方法作为参数传递,但没有成功。例如,我尝试过选择器[self.myframework MyMethod:@selector(onSuccess :),@selector(onError::)]];但Xcode表示:“将'SEL'发送到不兼容类型'void(^ _ Nonnull)(NSString * _Nonnull __strong)的参数”
最佳答案
如您所指出的,根据*-Swift.h
标题,Swift的MyMethod
作为块以参数的形式导入到Objective-C中。因此,您需要传递包装了Objective-C方法调用的块,如下所示:
[self.myframework MyMethod: ^ (NSString * s){ [self onSuccess:s]; }
errorCallback: ^(NSString * s1, NSString * s2) { [self onError:s1:s2]; }];
有关Objective-C块的更多信息,请参见此处:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html