ios - NSObject 传递给 JavaScriptCore 后未释放

标签 ios swift javascriptcore

我正在创建一个 JSContext 并评估一段简单的 javascript...

function test(obj) {
}

接下来,我将创建一个 NSObject,它只包含 INITDEINIT 函数。

当我调用 javascript Test 函数并传入 NSObject 时,NSObjects DEINIT 方法永远不会被调用。我不确定为什么在测试函数执行后没有任何东西可以让它保持事件状态时它没有被释放。

Swift Playground

import UIKit
import JavaScriptCore

/**************************/
/******* SwiftObject ******/
/**************************/
@objc protocol SwiftObjectExport: JSExport {
}

class SwiftObject: NSObject, SwiftObjectExport {
    override init() {
        super.init()
        print("[INIT] SwiftObject")
    }

    deinit {
        print("[DEINIT] SwiftObject")
    }
}

/**************************/
/******** Main ************/
/**************************/

// DEINIT does NOT fires with this test
func test() {
    let jsContext = JSContext()
    jsContext?.evaluateScript("function test(obj) { } ")

    let obj = SwiftObject()
    jsContext?.objectForKeyedSubscript("test").call(withArguments: [obj])
}

// DEINIT fires with this test
func test2() {
    let jsContext = JSContext()
    jsContext?.evaluateScript("function test(obj) { } ")

    let obj = SwiftObject()
}


print("Running test 1...")
test() // DEINIT does NOT fires with this test

print("Running test 2...")
test2() // DEINIT fires with this test

最佳答案

在实际应用程序中,所有代码都包装在自动释放池中。在 Playground ,情况并非如此。

只需在您的测试代码周围添加一个自动释放池,即可解决您的问题:

autoreleasepool {
    print("Running test 1...")
    test()

    print("Running test 2...")
    test2()

    print("Inside autorelease pool")
}

print("Outside autorelease pool")

输出:

Running test 1...
[INIT] SwiftObject
Running test 2...
[INIT] SwiftObject
[DEINIT] SwiftObject
Inside autorelease pool
[DEINIT] SwiftObject
Outside autorelease pool

关于ios - NSObject 传递给 JavaScriptCore 后未释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39792633/

相关文章:

iOS 验证得到 Main_iPhone~iphone.storyboardc was not found

ios - 确定 UIStackView 内容大小

ios - 无法根据所选数组更新行数?

ios - 使用 AWS SDK 在 Swift 中包含未找到 sqlite3.h 的非模块化 header 和文件

arrays - UITableView SearchBar过滤查询

ios - Firebase FCM 最初无法工作,但如果打开应用程序,则可在 3-4 次后工作

ios - 为什么我不能设置暴露给 JavaScriptCore 的 Swift 字典项?

ios - JavaScriptCore 除了 'hello, world' 之外不工作

ios - 如何更改现有背景颜色的 Alpha channel