swift playground / deinit {}中的内存泄漏并未始终如一地调用 [英] Memory leaks in the swift playground / deinit{} not called consistently
问题描述
ARC对象删除似乎在Swift Playground中不一致。它是一个bug还是设计?
ARC object deletion seems to be inconsistent in the Swift Playground. Is it a bug or by design?
考虑这个类:
class Test {
var name: String
init(name:String){
self.name = name
println("\(name) initialized")
}
deinit{
println("\(name) deinitialized")
}
}
当我从操场上调用它时(不是命令行REPL,请参阅下面的评论):
When I call it from the playground (not the command line REPL, see comment below):
var t1 = Test(name: "t1")
var t2 : Test? = Test(name: "t2")
t2 = nil
我只看到初始化消息在控制台中:
I see only initialization messages in the console:
t1 initialized
t2 initialized
缺少的是t2的deinit。
What's missing is deinit of t2.
当我在应用程序中运行它时(例如,应用代表的输入) ),输出与ARC删除一致(即t1 init,然后t2,t2 deinit然后t1,因为整个调用块超出范围):
When I run it in an app (e.g. entry of app delegate), I the output is consistent with ARC deletion (i.e. t1 init, then t2, and t2 deinit and then t1, since the entire invocation block goes out of scope):
t1 initialized
t2 initialized
t2 deinitialized
t1 deinitialized
最后,在命令行REPL中(请参阅下面的注释以访问REPL),结果是明确的,即:t1由于其顶级范围而处于活动状态,但是t2被ARC删除,如人们会期待。
Finally, in the command line REPL (see comment below for accessing the REPL), the results are consisent, i.e.: t1 is alive due to its top level scope, but t2 is ARC deleted, as one would expect.
1> class Test {
2. var name: String
3. init(name:String){
4. self.name = name
5. println("\(name) initialized")
6. }
7. deinit{
8. println("\(name) deinitialized")
9. }
10. }
11> var t1 = Test(name: "t1")
t1 initialized
t1 initialized
t1 deinitialized
t1: Test = {
name = "t1"
}
12> var t2 : Test? = Test(name: "t2")
t2 initialized
t2 initialized
t2 deinitialized
t2: Test? = (name = "t2")
13> t2 = nil
t2 deinitialized
14> t1
$R2: Test = {
name = "t1"
}
15> t2
$R3: Test? = nil
推荐答案
我们比较了ARC /删除异议应用场景和游乐场内。我们的测试代码使用在特定范围内外创建的对象。我们还嵌套了测试对象以测试多嵌套作用域。
We compared ARC/deletion of objection in an app scenario and within the Playground. Our test code used object created inside and outside a particular scope. We also nested the tester object to test multi-nested scoping.
我们看到应用场景在cue上删除了对象(第0个引用),而Playground场景删除了一些,但保留了多数对象(无论范围如何,但在多次运行中显然是一致的)。
We saw that the app scenario deletes objects right on cue (zeroth reference) whereas the Playground scenario deletes a few, but holds on to a majority of objects (irrespective of scope, but apparently consistent over multiple runs).
Playground可能会保留对象以便为其辅助GUI输出(和/或其播放功能)提供服务。
The Playground probably holds on to objects in order to service its assistant GUI output (and/or its playback feature).
参见博文这里。
这篇关于swift playground / deinit {}中的内存泄漏并未始终如一地调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!