我正在使用 cocos2d-x 在 C++ 中创建一个应用程序。对于一些集成工作,我需要调用 Objective C 代码,通过从 Objective C 调用 C++ 回调方法实现异步响应。
TLDR;每当回调完成时,我应该如何将 C++ 释放到 Objective C 桥?我应该将桥实现为静态成员变量吗?
对于从 C++ 到 Objective C 的基本部分,我遵循了 Jesús Bosch's lead ,对于从 Objective C 调用 C++ 回调,我遵循了他的 colleagues post .
基本上,我已经完成了以下设置。
首先,我们有MyApp.h
class MyApp
{
public:
static void buttonChosen(int index);
void callObjC();
// ...
}
和 MyApp.cpp
,负责启动 Objective C 代码。
void MyApp::buttonChosen(int index)
{
log("Button choosen: %d", index);
}
void MyApp::callObjC()
{
iOSBridge::iOSHelper* bridge = new iOSBridge::iOSHelper();
bridge->ShowAlert(buttonChosen);
// delete bridge;
}
然后,我有了桥,iOSBridge.h
namespace iOSBridge{
class iOSHelper {
public:
void(*callback)(int index);
iOSHelper() { }
void ShowAlert(void(*callback)(int));
};
}
及其实现iOSHelper.cpp
#include "iOSHelper.h"
#import "IsolatedAlert.h"
namespace iOSBridge{
void iOSHelper::ShowAlert(void(*callback)(int index))
{
this->callback = callback;
IsolatedAlert* instance = [IsolatedAlert new];
[instance showAlert: this];
}
}
最后是IsolatedAlert.h
#import <UIKit/UIKit.h>
#import "iOSHelper.h"
typedef struct iOSBridge::iOSHelper iOsType;
@interface IsolatedAlert : UIViewController
-(void)showAlert:(iOsType*)callback;
@end
及其实现IsolatedAlert.mm
#import "IsolatedAlert.h"
iOsType* staticPointer;
@implementation IsolatedAlert
-(void)showAlert:(iOsType*)callback
{
staticPointer = callback;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title?"
message:@"Message?"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK", nil];
[alert show];
[alert release];
}
-(void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
staticPointer->callback(buttonIndex);
}
@end
现在,我的问题是:每当调用 buttonChosen()
时,我应该如何释放 iOSBridge::iOSHelper* bridge
?是否可以将其作为静态成员实现,只要我保证在任何时候都不会实例化多个 MyApp
实例?谢谢!
最佳答案
通常C++ way of releasing an instance用new
创建就是使用delete
关键字:
void MyApp::buttonChosen(int index)
{
log("Button choosen: %d", index);
delete bridge;
bridge = NULL;
}
最好在删除后将指针NULL
,以确保在delete
后使用对象时应用程序以一致的方式运行(崩溃)。如果您不这样做,您的应用程序可能会工作一段时间、产生不正确的结果、表现出奇怪的行为或随机崩溃,或者出现上述所有情况。
啊,当然你应该让桥指针成为你的 App 类的成员变量。
#include "iOSHelper.h"
class MyApp
{
public:
static void buttonChosen(int index);
void callObjC();
// ...
protected:
iOSBridge::iOSHelper* bridge;
}
您还应该考虑将现有方法设为 protected
或 private
,因为 buttonChosen 可能不是您希望能够从 MyApp 实异常(exception)部调用的方法。
关于c++ - 从 Objective C 调用 C++ 回调后如何释放桥接对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22037970/