Reputation: 224
I want to make a delegate in separate class like:
class MapViewAnnotationDelegate: NSObject, SomeDelegate { //...}
and then in my controller I want to assign:
someView.delegate = MapViewAnnotationDelegate()
but the delegate is nil... how to achieve such effect? I read something about strong in Objective-C but as far as I happen to know the strong is default in Swift.
Upvotes: 1
Views: 922
Reputation: 299345
What you're doing is fine, but you need something to hold onto your instance. delegate
properties by tradition are weak
, so they don't ensure that the object is retained. Something else must retain it. The most common solution is to add a property to the class that owns someView
, and assign your MapViewAnnotationDelegate
to that property before assigning it as the delegate. That way it won't be deallocated as long as the containing objet lives. But anything that retains it is ok.
Your current code currently does this:
One way this may look would be like this:
class Owner {
let mapViewAnnotationDelegate = MapViewAnnotationDelegate()
let someView: ...
init() {
someView.delegate = mapViewAnnotationDelegate
}
}
In this configuration, Owner
(which is the owner of someView
) holds onto the delegate for its lifetime.
Upvotes: 1