Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Calling JS functions on NSString #9

ccgus opened this Issue Aug 6, 2012 · 5 comments


None yet
2 participants

ccgus commented Aug 6, 2012

It'd be great if it was possible to call JS Functions on NSObjects where it makes sense, like NSString:

//var s = "Hello World!" // this will work
var s = NSString.stringWithString_("Hello World!");  // This will not

function replacerFunction(match, p1, p2, p3, offset, string) {
    return "Mocha";

// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
// TypeError: 'undefined' is not a function (evaluating 's.replace("World", replacerFunction)')
s = s.replace("World", replacerFunction); 


logancollins commented Aug 6, 2012

Hmm. This is an interesting idea. The runtime currently immediately checks the object for the -replace: method, and finding none, fails.

For this to work, the runtime would have to know what ObjC⟷JS types could be implicitly converted (for example, it would have to know that it should interpret an NSString as a JS String in the case that it doesn't have a matching method).

I believe PyObjC solves this by mixing in all of Python's string methods into NSString at runtime.

Must investigate further...


ccgus commented Aug 7, 2012

I'll have to peek into JSCocoa to see what it's doing.


ccgus commented Oct 25, 2012

JSCocoa does a special check just for strings:
https://github.com/parmanoir/jscocoa/tree/master/JSCocoa (line 4417, comment "// (First) Last chance before exception : try treating callee as a Javascript string")

So it's doing runtime checks.


ccgus commented Oct 25, 2012

OK, I've got some code:

(the leak on line 1560 is fixed in the next commit).

Does this look reasonable?


logancollins commented Nov 1, 2012

This looks like it would be fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment