在 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
视图控制器.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中使用它。
相关文章:
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 无法理解代码背后的逻辑,这是在两个给定数字之间生成素数的优化问题
- 单词之间的莫尔斯电码空格问题
- 玩家移动和碰撞之间的交互问题
- 在 Objective-C 和 Swift 之间委托问题
- OpenGL在Ortho和特点问题之间切换
- 特征,制造和cmake之间的问题(可能是cmake错误)
- OPENCV MAT问题:直方图和此循环之间的差异
- 计算当前日期和用户输入日期问题之间的天数
- 如何解决删除其他人之间共享的对象的问题
- 类型定义之间的兼容性问题
- C 如何在Typedef模板和类之间修复依赖关系问题
- Visual Studio和Xcode之间的Chaiscript字符串问题
- 使用指针和结构C 计算两个点之间的距离,分割故障问题
- Mac和Linux机器之间的正则兼容性问题
- 合并排序问题,在方法之间传递数组
- 正确处理字节对齐问题 - 通过UDP在16位嵌入式系统和32位桌面之间
- 相同大小的2D和1D阵列之间的内存或执行问题
- 超声波传感器和以太网屏蔽Arduino之间的问题
- 在 Xcode 和 Visual Studio 之间移动时出现问题