我在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
,则会正常解除分配。