Reputation: 1255
I have a problem with delegates in Swift (OSX). I have a view, connected to a delegate through a weak reference. Simplified code could be like this:
protocol MyProtocol: class {
func protocolFunc() -> Int
}
class MyController : MyProtocol {
func protocolFunc() -> Int { return 2 }
}
class MyView : NSView {
weak var delegate: MyProtocol?
func grabData {
var data = delegate?.protocolFunc()
}
}
When delegate?.protocolFunc()
is called, the app crashes saying "bad access". It's like if the MyController instance had disappeared... But it has not. The MyController instance lives in a NSDocument subclass; and view's delegate is properly set.
The crash goes away if I declare the delegate to be strong
. But the thing is I want the delegate to be weak
. What's going on? To my eyes, the weak reference should work.
Upvotes: 0
Views: 434
Reputation: 760
A temporary alternate solution would be to change this:
weak var delegate: MyProtocol?
to this:
weak var delegate: MyController?
Of course it defeats the purpose of MyProtocol, however, it allows you to use pure Swift classes while we wait for a proper fix for this.
Upvotes: 0
Reputation: 4566
At the time of writing (Xcode 6 Beta 5), there's a bug with weak delegates. For the time being, all you can do until it is fixed is to change protocol MyProtocol: class
to @objc protocol MyProtocol
and avoid using any pure Swift classes in your protocol.
Upvotes: 1