cocos2d-js 调用 xcode objective-c function

最近写一个cocos2d 的游戏, 由于cocos2d-js 的cross platform 特性(web/ios/android),决定使用js。
由于js 游戏需要用到蓝牙,所以需要调用oc 来call bluetooth function, 所以需要在js 中添加jsb reflection call
official website 可以使用(http://www.cocos2d-x.org/docs/manual/framework/html5/v3/reflection-oc/zh), 所以就走上了不归路
看到网上有许多讲andrioid, java-js 相互调用的,但是却没有完整的将oc-js 怎样通过jsb 相互调用的。一开始看了andrioid教程,把.h 和.m 文件放错了位置。jsb.reflection.callStaticMethod永远得到return error -5
而且在网上居然查不到这个error。倒是有人说有return error -4,是放错了位置. 结果我试了好几个地方都出这个return error -5 !!! 而且我search xcodeproj 里面居然说only android platform supported 。。。

仔细研究了一下xcodeproj structure 倒是有人分析这个的。发现其他的main.m 文件在另外一个folder 里面, 试一试吧,反正也出不来



居然成功啦!

JS code:
var ret = jsb.reflection.callStaticMethod("NativeOcClass","addTwoNumber");

cc.log("return value:"+ret);

oc header file:
#import <Foundation/Foundation.h>
@interface NativeOcClass : NSObject
+(BOOL)callNativeUIWithTitle:(NSString *)title andContent:(NSString *)content;
+(float)addTwoNumber;
@end

oc implementation file:
#import <Foundation/Foundation.h>
#import <NativeOcClass.h>
@implementation 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;
}
+(float) addTwoNumber{
    return 1.1;
}
@end

结果:
JS: return value:1.100000023841858

评论

此博客中的热门博文

Embedded System interview Question

MicroKernel & Exokernel 操作系统未来可能的发展

中国城市房地产分析