Question

This project is about the make a communication between javascript and native objc method.And I heard that Apple introduced the JavascriptCore in IOS7. So, here is my sample html

<html>
<head>
</head>
<body>
    <script>
        function test2()
        {
            TASK.test2();
        }
    </script>
    <form>

        <button type='button' onclick='TASK.test()'>Test</button>

    </form>

</body>
</html>

and in my native code. i included this

@protocol TASKExports <JSExport>
-(void)test;
-(void)test2;

on webViewDidFinishLoad I assigned the javascriptContext to my class as i implemented the JSExports.

    JSContext *ctx = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
ctx[@"TASK"] = self;

run the program, everything goes fine, but when I pop this viewcontroller. found that it is not dealloc and something is retain it. I have try few ways to figure it out.

Approach 1 , remove the scrtpt tag in html. Remove this

<script>
            function test2()
            {
                TASK.test2();
            }
        </script>

Second, is command this line

ctx[@"TASK"] = self;

I pretty sure it is retained by the javascript context. But which part is wrong?? many thanks

Was it helpful?

Solution

finally I got it. instead of this

ctx[@"TASK"] = self;

I do this one by one

ctx[@"TAST_test1"] = ^{
    Code goes here
};
ctx[@"TAST_test2"] = ^{
    Code goes here
};

OTHER TIPS

You will end up in an retain cycle if you pass self or an instance which is property of self it to your JSContext.

ctx[@"TASK"] = self.task; // don´t do, that leaks
ctx[@"TASK"] = self; // that also leaks

To go the comfortable way and call the functions declared in your TASKExports protocol directly from JavaScript you have to pass a "clean and non-retained" instance. It´s the only way to avoid retain-cycles.

ctx[@"TASK"] = [[Task alloc] init]; // that´s the way

To interact with your context running class its also possible to use delegation:

ctx[@"TASK"] = [[Task alloc] initWithDelegate:self]; // also works with blocks
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top