我正在编写一个 Objective-C 类,但它使用了一个用 C 编写的 API。这很好,因为将 C 调用与 Objective-C 调用混合会导致一些问题。
但是其中一个 API 调用需要回调方法(示例):
success = CFHostSetClient(host, MyCFHostClientCallBack, &context);
其中 MyCFHostClientCallBack
是这样定义的 C 函数:
static void MyCFHostClientCallBack(CFHostRef host, CFHostInfoType typeInfo, const CFStreamError *error, void *info);
最佳答案
混合 C 和 Objective-C 方法和函数是可能的,这是一个在 iPhone 应用程序中使用 SQLite API 的简单示例:( course site )
Download the Zip file (09_MySQLiteTableView.zip)
C 函数需要在 Objective-C (.m) 文件中的 @implementation
之外声明。
int MyCFunction(int num, void *data)
{
//code here...
}
@implementation
- (void)MyObjectiveCMethod:(int)number withData:(NSData *)data
{
//code here
}
@end
因为 C 函数在 @implementation
之外,它不能调用像
[self doSomething]
并且无法访问 ivars。
只要回调函数采用 userInfo
或 context
类型参数(通常为 void*
类型),就可以解决此问题.这可用于将任何 Objective-C 对象发送到 C 函数。
如 sample code , 这可以通过正常的 Objective-C 操作来操作。
另外请阅读这个答案:Mixing C functions in an Objective-C class
https://stackoverflow.com/questions/801976/