从swift调用objective-C typedef块
我正试图从swift调用一个方法。 该方法采用Objective-C编写的单例
头文件中的块:
typedef void(^VPersonResultBlock)(Person *person, NSError *error); - (void)askForMe:(VPersonResultBlock)block;
这是该方法的实现。
- (void)askForMe:(VPersonResultBlock)block { if (_me) block(_me,nil); else { [Person getMeWithBlock:^(PFObject *person, NSError *error) { if (!error) { _me = (Person *)person; block(_me,nil); } else if (error) { block(nil,error); } else { NSDictionary *userInfo = @{ NSLocalizedDescriptionKey: NSLocalizedString(@"Operation was unsuccessful.", nil), NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"The operation failed to retrieve the user.", nil), NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Check your network connection and try again", nil) }; NSError *error = [[NSError alloc] initWithDomain:@"VisesAsyncErrorDomain" code:-10 userInfo:userInfo]; block(nil,error); } }]; } }
在Objective-C中,我可以调用它,它可以自动完成而不会混淆。
[[VDataStore instance] askForMe:^(Person *person, NSError *error) { // do things with myself that aren't strange }];
现在让我们说我想从swift调用相同的方法。 设置了桥接头,导入了头文件,但swift的期望令人困惑。
VDataStore.askForMe(VDataStore)
这是自动填充选项中显示的内容
(VPersonResultBlock!) -> Void askForMe(self: VDataStore)
我希望的是,这是为了自动完成关闭,虽然它似乎正确地看到了所有的信息,它期待的是没有排列什么目标-C似乎理解。
如何从swift中正确调用?
直接将你的ObjC调用代码翻译成Swift
VDataStore.instance().askForMe() { person, error in // do things with myself that aren't strange }
您的问题是askForMe
是实例方法,但您正在从类对象VDataStore.askForMe
访问。 Swift将为您提供一个以实例作为输入的函数对象。