【问题标题】:Calling objective-C typedef block from swift从swift调用objective-C typedef块
【发布时间】:2014-12-04 20:10:24
【问题描述】:

我正在尝试从 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)

我所希望的是,它可以自动完成到一个闭包中,虽然它似乎正确地看到了所有信息,但它所期望的与 Objective-C 似乎理解的不一致。

如何从 swift 中正确调用它?

【问题讨论】:

    标签: ios objective-c swift closures objective-c-blocks


    【解决方案1】:

    直接将你的 ObjC 调用代码翻译成 Swift 是

    VDataStore.instance().askForMe() {
        person, error in 
        // do things with myself that aren't strange
    }
    

    您的问题是 askForMe 是实例方法,但您正在从类对象 VDataStore.askForMe 访问。 Swift 会给你一个函数对象,它接受一个实例作为输入。

    【讨论】:

    • 不敢相信我错过了,解决了它;谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 2014-07-27
    • 1970-01-01
    相关资源
    最近更新 更多