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

Delegate issue between Objective-C and Swift

本文关键字:问题 之间 Swift Objective-C      更新时间:2023-10-16

我即将了解 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

视图控制器.swift:

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

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

协议只不过是一个类必须实现的一组需求(方法(。我们说一个类符合协议。

所以在你的静态函数test()中,如果你周围没有实例/对象(这里是一个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

有很多关于协议和委派模式的资源,比如 Apple 的本指南。仔细阅读他们如何在Cocoa & Cocoa Touch中使用它。