后台线程中的自变异 Swift 结构 [英] Self-mutate Swift struct in background thread

查看:54
本文介绍了后台线程中的自变异 Swift 结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个结构体,该结构体必须作为后台操作的一部分发生:

Assume we have a struct capable of self-mutation that has to happen as part of a background operation:

struct Thing {
    var something = 0
    mutating func operation(block: () -> Void) {            

        // Start some background operation
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {

            // Mutate self upon background task completion
            self.something += 1
            block()

        }

    }
}

现在,当我在上下文中使用这样的结构时:

Now, when I use such a struct in context:

var myThing = Thing()
myThing.operation {
    println(myThing.something)
}

println 给了我 0,就好像 myThing 从未发生过变异一样.从 dispatch_async 中打印 self.something 显然会产生 1.

The println gives me 0, as if myThing was never mutated. Printing self.something from within the dispatch_async obviously yields 1.

我如何解决这个问题,最好不必在 operation 竞争块中传递更新结构的 self 并覆盖主上下文中的原始变量?

How do I work around this issue, preferably without having to pass the updated struct's self in the operation competition block and overriding the original variable in the main context?

// Ew
var myThing = Thing()
myThing.operation {
    (mutatedThing) in
    myThing = mutatedThing
    println(myThing.something)
}

推荐答案

我要添加第二个答案,因为我的第一个答案解决了不同的问题.

I'm adding a second answer because my first answer addressed a different point.

我刚刚在与您几乎相同的情况下遇到了这种困难.

I have just encountered this difficulty myself in circumstances almost identical to yours.

在努力工作并努力找出发生了什么并修复它之后,我意识到问题基本上是使用值类型而应该使用引用类型.

After working and working and working to try to find out what was going on, and fix it, I realized that the problem was, basically, using a value type where a reference type should be used.

闭包似乎创建了结构的副本并对其进行操作,而原始结构保持不变——这更符合值类型的行为.

The closure seems to create a duplicate of the struct and operate on that, leaving the original untouched--which is more in line with the behavior of a value type.

另一方面,期望的行为是让在闭包中执行的动作被闭包外的环境保留——换句话说,两个不同的上下文(在闭包内和在闭包外)需要引用相同的对象——更符合引用类型的行为.

On the other hand, the desired behavior is for the actions performed in the closure to be retained by the environment outside the closure--in other words two different contexts (inside the closure and out of it) need to refer to the same objects--which is more in line with the behavior of a reference type.

长话短说,我把结构改成了一个类.问题消失了,不需要其他代码.

Long story short, I changed the struct to a class. The problem vanished, no other code needed.

这篇关于后台线程中的自变异 Swift 结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆