UIActivity和UIActivityViewController带来神秘的内存泄漏

时间:2016-05-31 14:35:18

标签: ios swift memory memory-leaks uiactivity

我在iOS上使用Swift遇到了内存泄漏。

这是一个精简的可运行示例 - 您可以点按屏幕以显示共享表,BadActivity每次都会泄漏。

import UIKit

class ViewController: UIViewController {
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let activity = ShareController(activityItems: [""],  applicationActivities: [BadActivity(), GoodActivity()])
        self.showViewController(activity, sender: nil)
    }
}

class ShareController: UIActivityViewController {
    deinit { print("ShareController deinit.") }
}

class GoodActivity: UIActivity {
    override func activityTitle() -> String { return "Good" }
    deinit { print("Good deinit. This is printed.") }
}

class BadActivity: UIActivity {
    override func activityTitle() -> String { return "Bad" }
    deinit { print("Bad deinit. This is never printed.") }

    override func canPerformWithActivityItems(activityItems: [AnyObject]) -> Bool {
        return true
    }

    override func performActivity() {
        self.activityDidFinish(true)
    }
}

无论您是取消对话框还是按导出,BadActivity都已实例化但从未取消分配 - 控制台输出为ShareController deinit. Good deinit.

但是,如果您使BadActivity.canPerformWithActivityItems返回false而不是true,则会正常解除分配。

0 个答案:

没有答案