分派到串行队列后,弱引用变为 nil

Weak reference becomes nil after dispatch into serial queue

我玩弄 Swift 游乐场并注意到以下问题:

下面的代码描述了一系列以下列方式相互连接的对象:

objectC --> ObjectB -- weak ref to another C --> another C --> Object B 等..

每个对象C由

组成
- a ref to a object B 
- a weak ref to a delegate => this one becomes nil!!

每个对象B由

组成
- A var integer
- A weak ref to another object C

代码执行以下操作:

objectC 调用一个函数,例如 run(),它将计算 (objectB.weak_ref_to_another_C),并在串行队列中调用 objectB.weak_ref_to_another_C.run()

调用.run()几次后,C的委托神秘地变成了nil....

知道我做错了什么吗?要启动代码,只需在 Swift 游乐场上调用 test_recursive_serial()

let serialQueue = DispatchQueue(label: "myQueue");

public protocol my_protocol:class  {
    func do_something(ofValue:Int,completion:((Int) -> Void))
}

public class classA:my_protocol {

    public let some_value:Int;

    public init(value:Int){
        self.some_value = value;
    }
    public func do_something(ofValue:Int,completion:((Int) -> Void)) {
        print("A:\(some_value) in current thread \(Thread.current) is executing \(Thread.current.isExecuting)");
        if self.some_value == ofValue {
            completion(ofValue);
        }
    }

}

public class classB {

    public weak var jump_to_C:classC?;

    public var value:Int = 0;

}


public class classC {
    weak var delegate:my_protocol?{
        willSet {
            if (newValue == nil) { print("target set to nil") }
            else { print("target set to delegate") }
        }
    }

    var someB:classB?

    public func do_something_else() {
        print(self.delegate!)
    }

    public func do_another(withValue:Int,completion:((Int) -> Void)) {

    }

    public func run(completion:@escaping ((Int) -> Void)) {
        print("\(self.someB?.value)");
        assert(self.delegate != nil, "not here");
        if let obj = someB?.jump_to_C, obj !== self  {
            someB?.value += 1;
            print("\(someB!)")
            usleep(10000);
            if let value = someB?.value, value > 100 {
                completion(someB!.value);
            } else {
                serialQueue.async {
                    print("lauching...")
                    obj.run(completion: completion);
                }
            }
        }else{
            print("pointing to self or nil...\(someB)")
        }
    }
}


public func test_recursive_serial() {

    let my_a = classA(value:100);

    let arrayC:[classC] = (0..<10).map { (i) -> classC in
        let c = classC();
        c.delegate = my_a;
        return c;
    }

    let arrayB:[classB] = (0..<10).map { (i) -> classB in
        let b = classB();
        let ii = (i + 1 >= 10) ? 0 : i + 1;
        b.jump_to_C = arrayC[ii]
        return b;
    }

    arrayC.forEach { (cc) in

        cc.someB = arrayB[Int(arc4random())%arrayB.count];
    }

    arrayC.first!.run() { (value) in
        print("done!");
    }

}

重要说明:如果 test_recursive_serial() 内容是直接从 playground 调用的,即不是通过函数,则不会出现此问题。

编辑:您需要将 'PlaygroundPage.current.needsIndefiniteExecution = true' 添加到 playground 代码中。

编辑:好的,我觉得我需要添加这个。我这边犯了一个大错误,test_recursive_serial() 没有保留任何被调用对象的引用,所以很明显,在代码离开函数后它们都变成了 nil。因此问题。感谢 Guy Kogus 指出这一点。

最终编辑:添加这个,希望它能有所帮助。 Swift 游乐场非常适合试驾代码,但有时会变得非常繁忙。在当前问题中,解决方案需要先设置变量,然后将它们传递给 test_recursive_serial(),这反过来又增加了游乐场的聊天外观。这是在处理各种风格的异步函数时保持代码整洁和独立的另一种选择...

如果您有一个异步任务 - 一个不适合 URL fetch 的任务 - 说:

myObject.myNonBlockingTask(){ print("I'm done!"}

首先,在文件顶部包含 XCTest。

import XCTest

然后添加以下内容:

func waitForNotificationNamed(_ notificationName: String,timeout:TimeInterval = 5.0) -> Bool {
    let expectation = XCTNSNotificationExpectation(name: notificationName)
    let result = XCTWaiter().wait(for: [expectation], timeout: timeout)
    return result == .completed
}

最后,将完成块更改为:

myObject.myNonBlockingTask(){
    print("I'm done!")
    let name = NSNotification.Name(rawValue: "foobar");
    NotificationCenter.default.post(name:name , object: nil)
}
XCTAssert(waitForNotificationNamed("foobar", timeout: 90));

完整的 playground 代码如下所示:

public func my_function() {
    let somevar:Int = 123
    let myObject = MyClass(somevar);
    myObject.myNonBlockingTask(){
        print("I'm done!")
        let name = NSNotification.Name(rawValue: "foobar");
        NotificationCenter.default.post(name:name , object: nil)
    }
    XCTAssert(waitForNotificationNamed("foobar", timeout: 90));
}

Playground 会等待通知后再继续,如果超时也会产生异常。在执行完成之前,所有本地创建的对象都将保持有效。

希望对您有所帮助。

主要问题是您正在 Playgrounds 中对此进行测试,它不一定能很好地处理多线程。从 this SO question 开始,将 test_recursive_serial 函数更改为:

arrayC.first!.run() { (value) in
    print("done! \(value)")
    XCPlaygroundPage.currentPage.needsIndefiniteExecution = false
}

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

while XCPlaygroundPage.currentPage.needsIndefiniteExecution {

}

(您需要在代码顶部添加 import XCPlayground 才能使其生效。)

如果您不添加该代码更改,那么 my_a 会在您离开该函数后被释放,这就是为什么 delegate 在第二次调用 [=] 时变为 nil 17=].

我还发现在 run 中,如果你不像这样在 else 情况下调用 completion 闭包:

public func run(completion:@escaping ((Int) -> Void)) {
    ...
    if let obj = someB?.jump_to_C, obj !== self  {
        ...
    }else{
        print("pointing to self or nil...\(someB)")
        completion(-1) // Added fallback
    }
}

然后程序就卡住了。通过添加它运行到最后,虽然我还没有真正弄清楚为什么。

此外,请删除所有 ;,这不是 Objective-C