草庐IT

ios - 将闭包保存为变量的理解

coder 2023-09-14 原文

我正在 Playground 上测试这段代码(我正在使用 UnsafeMutablePointers 来模拟取消初始化):

class TestClassA {

    func returnFive() -> Int {
        return 5
    }

    deinit {
        println("Object TestClassA is destroyed!") //this way deinit is not called
    }
}

class TestClassB {

    let closure: () -> Int

    init(closure: () -> Int) {
        self.closure = closure
    }

    deinit {
        println("Object TestClassB is destroyed!")
    }
}

let p1 = UnsafeMutablePointer<TestClassA>.alloc(1)
p1.initialize(TestClassA())

let p2 = UnsafeMutablePointer<TestClassB>.alloc(1)
p2.initialize(TestClassB(closure: p1.memory.returnFive))

p2.memory.closure()
p1.memory.returnFive()


p1.destroy()

但是,当我将 TestClassB 的初始化更改为:

p2.initialize(TestClassB(closure: {p1.memory.returnFive()}))

现在可以取消初始化 TestClassA。

谁能告诉我,这两者有什么区别

TestClassB(closure: p1.memory.returnFive)

TestClassB(closure: {p1.memory.returnFive()})

为什么在第二种情况下没有对 TestClassA 的强引用,所以它可以被取消初始化?

最佳答案

这里的问题是使用 UnsafeMutablePointer<SomeStruct>.memory .重要的是不要陷入认为 memory 的陷阱就像一个包含指向对象的存储属性,只要指针存在,它就会保持事件状态。尽管感觉像一个,但它不是,它只是原始内存。

这是一个只使用一个类的简化示例:

class C {
    var x: Int
    func f() { println(x) }

    init(_ x: Int) { self.x = x; println("Created") }
    deinit { println("Destroyed") }
}

let p = UnsafeMutablePointer<C>.alloc(1)
p.initialize(C(42))
p.memory.f()
p.destroy()   // “Destroyed” printed here
p.dealloc(1)
// using p.memory at this point is, of course, undefined and crashy...
p.memory.f()

但是,假设您复制了 memory 的值,并将其分配给另一个变量。这样做会增加对象的引用计数 memory指向(就像您复制了另一个常规类引用变量一样:

let p = UnsafeMutablePointer<C>.alloc(1)
p.initialize(C(42))
var c = p.memory
p.destroy()   // Nothing will be printed here
p.dealloc(1)
// c has a reference
c.f()
// reassigning c decrements the last reference to the original
// c so the next line prints “Destroyed” (and “Created” for the new one)
c = C(123)

现在,假设您创建了一个捕获 p 的闭包,并在 p.destroy() 之后使用它的内存被称为:

let p = UnsafeMutablePointer<C>.alloc(1)
p.initialize(C(42))
let f = { p.memory.f() }
p.destroy()   // “Destroyed” printed here
p.dealloc(1)
// this amounts to calling p.memory.f() after it's destroyed,
// and so is accessing invalid memory and will crash...
f()

但是,对于您的情况,如果您只是分配 p.memory.ff , 完全没问题:

let p = UnsafeMutablePointer<C>.alloc(1)
p.initialize(C(42))
var f = p.memory.f
p.destroy()  // Nothing will print, because
             // f also has a reference to what p’s reference
             // pointed to, so the object stays alive
p.dealloc(1)
// this is perfectly fine
f()
// This next line will print “Destroyed” - reassigning f means 
// the reference f has to the object is decremented, hits zero, 
// and the object is destroyed 
f = { println("blah") }

那怎么会f捕获值(value)?

正如@rintaro 所指出的,Swift 中的成员方法是柯里化(Currying)函数。想象一下没有成员方法。相反,只有常规函数和具有成员变量的结构。你怎么能写出等价的方法呢?你可能会这样做:

// a C.f method equivalent.  Using this
// because self is a Swift keyword...
func C_f(this: C) {
    println(this.x)
}
let c = C(42)
// call c.f()
C_f(c)  // prints 42

Swift 更进一步,“套用”了第一个参数,这样你就可以写成 c.f并获得绑定(bind) f 的函数到 C 的特定实例:

// C_f is a function that takes a C, and returns
// a function ()->() that captures the this argument:
func C_f(this: C) -> ()->() {
    // here, because this is captured, it’s reference
    // count will be incremented
    return { println(this.x) }
}

let p = UnsafeMutablePointer<C>.alloc(1)
p.initialize(C(42))
var f = C_f(p.memory)  // The equivalent of c.f
p.destroy()   // Nothing will be destroyed
p.dealloc(1)
f = { println("blah") } // Here the C will be destroyed

这等同于您原始问题代码中的捕获,应该显示为什么您没有看到原始 A 对象被销毁。

顺便说一句,如果你真的想使用闭包表达式来调用你的方法(假设你想在之前或之后做更多的工作),你可以使用变量捕获列表:

let p = UnsafeMutablePointer<C>.alloc(1)
p.initialize(C(42))
// use variable capture list to capture p.memory
let f = { [c = p.memory] in c.f() }
p.destroy()   // Nothing destroyed
p.dealloc(1)
f()   // f has it’s own reference to the object

关于ios - 将闭包保存为变量的理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28384805/

有关ios - 将闭包保存为变量的理解的更多相关文章

  1. ruby-on-rails - 如何使用 instance_variable_set 正确设置实例变量? - 2

    我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击

  2. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  3. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

  4. ruby-on-rails - Ruby 检查日期时间是否为 iso8601 并保存 - 2

    我需要检查DateTime是否采用有效的ISO8601格式。喜欢:#iso8601?我检查了ruby​​是否有特定方法,但没有找到。目前我正在使用date.iso8601==date来检查这个。有什么好的方法吗?编辑解释我的环境,并改变问题的范围。因此,我的项目将使用jsapiFullCalendar,这就是我需要iso8601字符串格式的原因。我想知道更好或正确的方法是什么,以正确的格式将日期保存在数据库中,或者让ActiveRecord完成它们的工作并在我需要时间信息时对其进行操作。 最佳答案 我不太明白你的问题。我假设您想检查

  5. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  6. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  7. ruby-on-rails - 使用 ruby​​ 将多个实例变量转换为散列的更好方法? - 2

    我收到格式为的回复#我需要将其转换为哈希值(针对活跃商家)。目前我正在遍历变量并执行此操作:response.instance_variables.eachdo|r|my_hash.merge!(r.to_s.delete("@").intern=>response.instance_eval(r.to_s.delete("@")))end这有效,它将生成{:first="charlie",:last=>"kelly"},但它似乎有点hacky和不稳定。有更好的方法吗?编辑:我刚刚意识到我可以使用instance_variable_get作为该等式的第二部分,但这仍然是主要问题。

  8. ruby - Rack:如何将 URL 存储为变量? - 2

    我正在编写一个简单的静态Rack应用程序。查看下面的config.ru代码:useRack::Static,:urls=>["/elements","/img","/pages","/users","/css","/js"],:root=>"archive"map'/'dorunProc.new{|env|[200,{'Content-Type'=>'text/html','Cache-Control'=>'public,max-age=6400'},File.open('archive/splash.html',File::RDONLY)]}endmap'/pages/search.

  9. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  10. CAN协议的学习与理解 - 2

    最近在学习CAN,记录一下,也供大家参考交流。推荐几个我觉得很好的CAN学习,本文也是在看了他们的好文之后做的笔记首先是瑞萨的CAN入门,真的通透;秀!靠这篇我竟然2天理解了CAN协议!实战STM32F4CAN!原文链接:https://blog.csdn.net/XiaoXiaoPengBo/article/details/116206252CAN详解(小白教程)原文链接:https://blog.csdn.net/xwwwj/article/details/105372234一篇易懂的CAN通讯协议指南1一篇易懂的CAN通讯协议指南1-知乎(zhihu.com)视频推荐CAN总线个人知识总

随机推荐