Instance Method

setObject:forKeyedSubscript:

Sets the specified JavaScript property of the context’s global object, allowing subscript setter syntax.

Declaration

- (void)setObject:(id)object forKeyedSubscript:(NSObject<NSCopying> *)key;

Parameters

object

The value to set for the JavaScript property.

key

The JavaScript property name to use in the context’s global JavaScript object.

Discussion

This method first constructs a JSValue object from the key parameter, then uses that value in JavaScript to set the property in the context’s global object.

Use this method (or Objective-C subscript syntax) to bridge native objects or functions for use in JavaScript. For example, the following code creates a JavaScript function whose implementation is an Objective-C block:

JSContext *context = [[JSContext alloc] init];
context[@"makeNSColor"] = ^(NSDictionary *rgb){
    float r = rgb[@"red"].floatValue;
    float g = rgb[@"green"].floatValue;
    float b = rgb[@"blue"].floatValue;
    return [NSColor colorWithRed:(r / 255.f) green:(g / 255.f) blue:(b / 255.f) alpha:1.0];
};

See Also

Accessing JavaScript Global State with Subscripts

- objectForKeyedSubscript:

Returns the value of the specified JavaScript property in the context’s global object, allowing subscript getter syntax.