JSCore的头文件中 有一些面向C的类和函数
- 原生值转换JS
JSValueRef NSObjectToJSValue( JSContextRef ctx, NSObject *obj ) {
JSValueRef ret = NULL;
// String
if ([obj isKindOfClass:NSString.class]) {
JSStringRef jstr = JSStringCreateWithCFString((CFStringRef)(NSString *)obj);
ret = JSValueMakeString(ctx, jstr);
JSStringRelease(jstr);
}
// Number or Bool
else if ([obj isKindOfClass:NSNumber.class]) {
NSNumber *number = (NSNumber *)obj;
if( strcmp(number.objCType, @encode(BOOL)) == 0 ) {
ret = JSValueMakeBoolean(ctx, number.boolValue);
}
else {
ret = JSValueMakeNumber(ctx, number.doubleValue);
}
}
// Date
else if ([obj isKindOfClass:NSDate.class]) {
NSDate *date = (NSDate *)obj;
JSValueRef timestamp = JSValueMakeNumber(ctx, date.timeIntervalSince1970 * 1000.0);
ret = JSObjectMakeDate(ctx, 1, ×tamp, NULL);
}
// Array
else if ([obj isKindOfClass:NSArray.class]) {
NSArray *array = (NSArray *)obj;
JSValueRef *args = malloc(array.count * sizeof(JSValueRef));
for( int i = 0; i < array.count; i++ ) {
args[i] = NSObjectToJSValue(ctx, array[i] );
}
ret = JSObjectMakeArray(ctx, array.count, args, NULL);
free(args);
}
// Dictionary
else if ([obj isKindOfClass:NSDictionary.class]) {
NSDictionary *dict = (NSDictionary *)obj;
ret = JSObjectMake(ctx, NULL, NULL);
for( NSString *key in dict ) {
JSStringRef jsKey = JSStringCreateWithUTF8CString(key.UTF8String);
JSValueRef value = NSObjectToJSValue(ctx, dict[key]);
JSObjectSetProperty(ctx, (JSObjectRef)ret, jsKey, value, kJSPropertyAttributeNone, NULL);
JSStringRelease(jsKey);
}
}
return ret ? ret : JSValueMakeNull(ctx);
}
网友评论