【问题标题】:Why error ''self' used before self.init call' when using DispatchQueue in init?为什么在 init 中使用 DispatchQueue 时在 self.init 调用之前使用错误“self”?
【发布时间】:2018-01-01 00:53:25
【问题描述】:

我在(Xcode 9) 下方的代码中遇到了这些错误:

convenience init(dictionary: [String: AnyObject], context: NSManagedObjectContext) {
    guard let entity = NSEntityDescription.entity(forEntityName: "Photo", in: context) else {
        fatalError("No Entity name Found")
    }

    DispatchQueue.main.async {
        self.init(entity: entity, insertInto: context)
        self.title = dictionary[FlickrClient.JSONResponseKeys.title] as? String
        self.path = dictionary[FlickrClient.JSONResponseKeys.mediumURL] as? String
    }
}

没有DispatchQueue.main.async 它可以正常工作,但我需要实现它,因为应用程序不是线程安全的。提前谢谢!

【问题讨论】:

  • 不要发布代码或错误的图片,将文本粘贴到您的帖子中。
  • 我做了,图片显示的错误在标题中

标签: ios iphone swift swift3


【解决方案1】:

问题是您在传递给DispatchQueue.main.async 的闭包内使用self。当您在闭包内使用self 时,它会被闭包捕获,这算作将self 传递给某物。在完成初始化 self 之前,您不能这样做。

另外,考虑一下。如果允许,初始化程序将在初始化实际完成之前完成,因为主线程仍有工作要做,并且初始化程序在切换后几乎就完成了。

如果您需要异步初始化某些东西,请改用工厂模式:

static func make(foo: Foo, bar: Bar, baz: Whatever, handler: (Widget) -> ()) {
    DispatchQueue.main.async {
        guard let thingy = Thingy(xyzzy: plugh) else { fatalError("I DON'T LIKE SPAM") }

        handler(Widget(thingy: thingy))
    }
}

【讨论】:

  • 我按照工厂模式,还是一样的问题。但是,我知道在闭包中使用 self 是如何导致这个问题的。我将审查和编辑代码。谢谢
猜你喜欢
  • 1970-01-01
  • 2020-09-20
  • 2019-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多