Objective-C 和 Swift 之间的委托问题

Delegate issue between Objective-C and Swift

我即将学习 Swift、Objective-C 和 C++ 的基础知识。我正在尝试在 Objective-C 和 Swift 之间架起一座桥梁,并设置一个合适的委托人 (MyDelegate)。

下面的代码工作得很好,但我在从静态函数调用 Swift 函数 callbackInteger() 时遇到了一些问题,例如:

MyFile.mm:

static void test() {
    // how to call callbackInteger?
}

MyFile.mm:

- (void)callbackToSwift:(int)testInteger {
    if (self.delegate != nil) {
        [self.delegate callbackInteger: testInteger];
    }
}

MyDelegate.h:

@protocol MyDelegate <NSObject>
- (void) callbackInteger: (int) testInteger;
@end

ViewController.swift:

class ViewController: UIViewController, MyDelegate {
    func callbackInteger(_ testInteger: Int) {
       print("testInteger: \(testInteger)");
    }
}

注意:我真的不知道如何使用委托调用来实现对callbackInteger函数的调用。

协议只不过是 class 必须实现的一组要求(方法)。我们说 class 符合协议。

所以在你的静态函数test()中,如果你周围没有instance/object(这里是ViewController),你就不能调用协议的方法。一种可行的方法(但不一定是漂亮的方法)是在某处存储(例如作为全局变量) ViewController 的实例,以便在函数中重用它。

像这样:

// Top of your file
#import <Foundation/Foundation.h>
// other headers...

id<MyDelegate> globalDelegate;

static void test() {
    [globalDelegate callbackInteger:42];
}

// rest of your file

有很多关于协议和委托模式的资源,例如 this guide from Apple。仔细阅读他们如何在 Cocoa & Cocoa Touch.

中使用它