Search code examples
iosjavascriptcore

JavascriptCore isn't calling function with arguments properly


I've made an iOS application to install & run javascript scripts and to do so, I'm using JavascriptCore. Some of my scripts are periodic, which means they are started every X seconds for example.

Pseudo-code example:

every('X seconds', function(event) {
   save(event.timestamp);
});

So far, everything was fine until I realized that after few minutes (~3min) the function I call starts ignoring my argument. I get "undefined" inside my save method ! It's working for some time and then...

Objective-c code:

[_executionContext evaluateScript:[NSString stringWithFormat:@"var myFunc = %@", _script]];
[_executionContext[@"myFunc"] callWithArguments:@[event.data]];

Explanation

  1. I evaluate the function(event) { ... } (script) string and save it inside myFunc object.
  2. I call this function with my event.data which exposes timestamp. Simple !

Note that even when event.timestamp returns undefined my event.data object isn't nil ! And I've found nothing wrong inside my objective-c code. I think that something is happening inside callWithArguments method or I'm missing something...

Data interface:

@protocol DataExports<JSExport>
@property (nonatomic) long timestamp;
@end

@interface APSData : MTLModel<DataExports>
@end

I've the same problem on device and emulator.

Is there something I'm doing wrong ?

Regards,


Solution

  • Ok, I've found a solution !

    Instead of using evaluationScript on my function everytime my event occur I save it once inside a map and I use it to call my function after. So basically:

    [_executionContext evaluateScript:[NSString stringWithFormat:@"var %@ = %@", _functionHash, _script]];
    _functionMap[_functionHash] = [_executionContext evaluateScript:_functionHash];
    

    And when needed, I call:

    [_functionMap[_functionHash] callWithArguments:@[event.data]];
    

    To me there is no difference with what I did before but it seems to work better...

    Edit: Well... It doesn't really work. Now it fails after 10 minutes..