Skip to content

Instantly share code, notes, and snippets.

@chen-hongzhi
Created August 10, 2013 17:46
Show Gist options
  • Select an option

  • Save chen-hongzhi/6201369 to your computer and use it in GitHub Desktop.

Select an option

Save chen-hongzhi/6201369 to your computer and use it in GitHub Desktop.
Determine if a JSValue is an instance of Array
// Modified from http://code.google.com/p/jsxobjc/source/browse/trunk/source/JSXore/JSXObjCInterpreter.m
@implementation JSValue (CHAdditions)
- (BOOL)ch_isArray
{
static dispatch_once_t onceToken;
static JSStringRef lengthString = NULL;
static JSStringRef arrayString = NULL;
dispatch_once(&onceToken, ^{
lengthString = JSStringCreateWithUTF8CString("length");
arrayString = JSStringCreateWithUTF8CString("Array");
});
if (![self isObject]) {
return NO;
}
BOOL result = NO;
JSContextRef context = [[self context] JSGlobalContextRef];
JSObjectRef object = (JSObjectRef)[self JSValueRef];
if (!JSObjectIsFunction(context, object) && !JSObjectIsConstructor(context, object)) {
if (JSObjectHasProperty(context, object, lengthString)) {
// get the context's Arrray constructor - make sure it is a constructor!
JSValueRef arrayConstructor = JSObjectGetProperty(context, JSContextGetGlobalObject(context), arrayString, NULL);
if (JSObjectIsConstructor(context, (JSObjectRef)arrayConstructor)) {
if (JSValueIsInstanceOfConstructor(context, object, (JSObjectRef)arrayConstructor, NULL)) {
// finally! We know that it is an array!
result = YES;
}
}
}
}
return result;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment