How to call Objective-C functions using JavaScript on iOS/Mac

In Cocos2d-JS v3.0 RC2, we'd like to introduce you the js to Objective-C reflection feature. Like we can call native functions on Java by JS, you can now invoke Objective-C Static Method in JS too.

var ojb = jsb.reflection.callStaticMethod(className, methodNmae, arg1, arg2, .....);

You can use jsb.reflection.callStaticMethod to call Native OC method by sending className methodName and parameters.

Notice: Please pay attention to Apple Developer Program License Agreement (section 3.3.2) when you use reflection features. The usage of respondsToSelector: and performSelector: might cause problem in App Store review process, here is a related discussion in React-Native's issue tracker.

Objective-C Class

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

Objective-C Method

+(BOOL)callNativeUIWithTitle:(NSString *)title andContent:(NSString *)content;

So the methodName should be callNativeUIWithTitle:addContent: which is the definition for this method, and don't forget the :. We cannot discuss the details here, but if you are interested, you can search for Objective-C programming guide for more details.

    +(NSString *)callNativeWithReturnString;

Useage

var ret = jsb.reflection.callStaticMethod("NativeOcClass", 
                                           "callNativeUIWithTitle:andContent:",
                                           "cocos2d-js", 
                                           "Yes! you call a Native UI from Reflection");
+(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;
}

Notice

Types supported for parameters and return value are limited in Cocos2d-JS reflection.

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