Cocos2d 與OC的互相調用

JS里面調用OC

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

對應的Oc代碼為:

    +(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;
    }

注意

在OC的實現中,如果方法的參數需要使用float、int、bool的,請使用如下類型進行轉換:

float,int 請使用NSNumber類型
bool請使用BOOL類型。
例如下面代碼,我們傳入2個浮點數,然后計算他們的合并返回,我們使用NSNumber而不是int、float去作為參數類型。

+(float) addTwoNumber:(NSNumber *)num1 and:(NSNumber *)num2{
    float result = [num1 floatValue]+[num2 floatValue];
    return result;
}

目前參數和返回值支持 int, float, bool, string,其余的類型暫時不支持。

OC中調用JS代碼

相關配置自行谷歌
語句為:

 NSInteger coins = [[currentProId stringByReplacingOccurrencesOfString:@"," withString:@""] integerValue];
  
    std::string jsCallStr = cocos2d::StringUtils::format("util.storeLayer.appBuySuccessed(%zd);", coins);

    ScriptingCore::getInstance()->evalString(jsCallStr.c_str());

其中util.storeLayer 是一個全局的layer.js.
appBuySuccessed 是方法,括號里面是參數.

附js調用oc返回

#define JSO_ERR_OK (0)
#define JSO_ERR_TYPE_NOT_SUPPORT   (-1)
#define JSO_ERR_INVALID_AEGUMENTS (-2)
#define JSO_ERR_METHOD_NOT_FOUND (-3)
#define JSO_ERR_EXCEPTION_OCCURRED (-4)
#define JSO_ERR_CLASS_NOT_FOUND (-5)
#define JSO_ERR_VM_FAILURE (-6)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容