本文为ios开发环境下js和obc相互调用的例子。
一 、js调用oc
js
if (cc.sys.isNative&&cc.sys.os==cc.sys.OS_IOS) {
let ret = jsb.reflection.callStaticMethod("AdMaster","showAd:title:","有志者事竟成","淡定");
}
oc建一个AdMaster文件,继承NSObject
.h文件
+(BOOL)showAd:(NSString *)str title:(NSString *)tit;
.m文件
+(BOOL)showAd:(NSString *)str title:(NSString *)tit{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:tit message:str delegate:nil cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
[alertView show];
return true;
}
二、oc调用js
OC调用js方法用ScriptingCore。 bool evalString(const char *string);
OC端:
ScriptingCore::getInstance()->evalString("startJsCocosScene002()");
js端:
function startJsCocosScene002(){
console.log("main.js....startJsCocosScene002...")
cc.director.runScene(new HelloWorldScene002());
return 1;
}
带参数的oc调用js
-(void)callJsEngineCallBack:(NSString*) funcNameStr withCmd:(NSString*) cmdStr withContent:(NSString*) contentStr
{
NSLog(@"callJsEngineCallBack...");
string funcName = [funcNameStr UTF8String];
string param001 = [cmdStr UTF8String];
string param002 = [contentStr UTF8String];
std::string jsCallStr = cocos2d::StringUtils::format("%s(\"%s\",\"%s\");",funcName.c_str(), param001.c_str(),param002.c_str());
NSLog(@"jsCallStr = %s", jsCallStr.c_str());
ScriptingCore::getInstance()->evalString(jsCallStr.c_str());
}
js
function jsEngineCallback(cmd,content){
console.log("...jsEngineCallback..." + cmd + "..." +content);
};