简体   繁体   English

如何在Swift中创建弱引用字典?

[英]How to create a dictionary of weak references in Swift?

I need to store delegates which are views in a dictionary. 我需要将代表视图的代表存储在字典中。 Now I want to hold them as weak references, So if the user quits the screen my dictionary won't be the one preventing those views to cleanup. 现在,我想将它们作为弱引用,因此,如果用户退出屏幕,我的词典将不会阻止这些视图进行清理。

I was trying to use the solution from: 我正在尝试使用以下解决方案:

How do I declare an array of weak references in Swift? 如何在Swift中声明弱引用数组?

But for some reason as soon as I add the line of code where I try to get the real delegate from the weak object: 但是由于某种原因,我在代码行中尝试从弱对象中获取真正的委托:

if let realDelegate = delegate.value {
    realDelegate.updateProgressBar(Int(progress * 100), aTaskIndentifier: downloadTask.taskIdentifier)
}

I get the following error in Xcode at compile time: 我在编译时在Xcode中收到以下错误:

Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1 命令/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc失败,退出代码为1

Do you know what is the problem with this solution? 您知道此解决方案有什么问题吗? Or maybe you could provide another solutions for this task? 也许您可以为此任务提供其他解决方案?

您可以使用NSHashTable.weakObjectsHashTable()代替内置的Swift字典。

Following works for me: 以下对我有用的作品:

struct WeakReference<T: AnyObject> {
    weak var value: T?
}
@objc protocol P { // Note @objc, class or AnyObject does not work
    var i: Int { get }
}
class CP: P {
    var i: Int = 0
}
let cP = CP() // Strong reference to prevent collection
let weakPD: [Int : WeakReference<P>] = [0 : WeakReference(value: cP)]
print("PD: \(weakPD[0]!.value!.i)") // 0

But note I had to use @objc. 但是请注意,我必须使用@objc。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM