0924wuyr
0924wuyr

Reputation: 13

how to call cocos2d-js method from objective-c

i am using cocos2d-js , that's a in purchase app,when purchase success ,i need to notify the message to cocos2d-js to update ui or something else,

i know call objective-c from cocos2d-js is like: in js:

jsb.reflection.callStaticMethod("objective-cClass","methodName:", "parm");

but,how to call cocos2d-js from objective-c...

Upvotes: 1

Views: 2037

Answers (2)

doubleevil
doubleevil

Reputation: 41

1:how js call objc methods like this, js call only static method

(1)//NativeOcClass.mm  filename
import <Foundation/Foundation.h>
@interface NativeOcClass : NSObject
+(BOOL)callNativeUIWithTitle:(NSString *) title andContent:(NSString *)content;
@end

@implement NativeOcClass
+(BOOL)callNativeUIWithTitle:(NSString *) title andContent:(NSString *)content{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:content delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
    [alertView show];
    return true;
}
@end

(2)for js file
var ret = jsb.reflection.callStaticMethod("NativeOcClass", 
                                           "callNativeUIWithTitle:andContent:", 
                                           "cocos2d-js", 
                                           "Yes! you call a Native UI from Reflection");

2:objc call js method

(1)js method,e.g.//Test.js
var Test={
          myMethod:function(){
              console.log("call js");
              }
          }
(2)objc //filename.mm
#include "cocos/scripting/js-bindings/manual/ScriptingCore.h"
....
-(void)callJsMethod
{
   jsval ret;
   ScriptingCore::getInstance()->evalString("Test.myMethod()", &ret);
}

Upvotes: 0

doubleevil
doubleevil

Reputation: 41

May it help someone, as we know, objective-c can easily call c++ methods, so we can use like this:

jsval ret;
ScriptingCore::getInstance()->evalString("CommonFun.setDiamond(88)", &ret);

and dont forget include head file, for cocos2d-x 3.8:

#include "cocos/scripting/js-bindings/manual/ScriptingCore.h"

Upvotes: 1

Related Questions