Cyclic references getting formed in this example, however I can't apply unowned or weak to protocol variables, what's the workaround in this situation.
protocol Report {
func done()
}
class Employee {
unowned var report: Report? //error here with using unowned or weak
func whenIAmDone() {
report.done()
}
}
class Supervisor: Report {
var employees: [Employee]?
init() {
for i in 1...5 {
var employee = Employee()
employee.report = self
employees?.append(employee)
}
}
func done() {
println("work done by...")
}
}
You need to declare your Report protocol as class-only by adding class to its declaration:
protocol Report: class {
func done()
}
You have a separate issue there, with disagreement between your choice of "weak" keywords and the report property being optional. Here's the rule: weak instances are always optional, unowned instances are never optional. Employee should look like this:
class Employee {
weak var report: Report? //error here with using unowned or weak
func whenIAmDone() {
report?.done()
}
}
or if you want report to be unowned, it would need to be a non-Optional, but then you need an initializer that can give it a value.
You have to declare your protocol as class-only like below.
protocol Report : class {
func done()
}
class Employee {
weak var report: Report?
func whenIAmDone() {
report?.done()
}
}
Read this to learn the difference between weak and unowned. What is the difference between a weak reference and an unowned reference?
Related
My view model is as such:
public class MainTabBarViewModel: MainTabBarInputs {
unowned var output: MainTabBarOutputs
...
}
where the view controller is this:
class ViewController: MainTabBarOutputs {
var viewModel: MainTabBarInputs!
}
I'm trying to write a unit test to test for the retain cycle:
class MainTabBarViewModelTests: XCTestCase {
var viewModel: MainTabBarViewModel!
var viewController: MockMainTabBarViewController!
func testRetainViewController() {
viewController = nil
// TODO how do you test this
expect(self.viewModel.output).to(beNil())
// crashes because I can't
// reference an unowned pointer that's deallocated.
}
I know if I changed my reference to be weak I could test this, but what if I wanted to leave it as unowned?
You can use a weak reference to the controller in the unit test, and if that reference becomes nil, then you don't have a retain cycle:
func testRetainViewController() {
weak var testRef = viewController
viewController = nil
expect(testRef).to(beNil())
}
You can easily validate the above approach by changing from unowned to strong and see that the test fails.
Looks like weak references will be disallowed in protocols. So what am I supposed to do if I wanna add a weak reference? Any better idea?
protocol PipelineElementDelegate: class {
func someFunc()
}
protocol PipelineElement {
weak var delegate: PipelineElementDelegate? { get set}
}
Simply remove the weak keyword from the protocol and declare the property as weak in the conforming type instead:
class SomeClass: PipelineElement {
weak var delegate: PipelineElementDelegate?
}
private weak var _delegate: SomeClassDelegate?
weak var delegate: SomeClassDelegate? {
get {
return _delegate
}
set {
_delegate = newValue
}
}
This is valid code. Is there is any sense in using weak keyword with computed delegate property? Logically no; how compiler will process through this code?
Is there is any sense in using weak keyword with computed delegate property?
Not only is it sensible to do so, but it’s important to do so. This computed property is your public interface to this private hidden property. If the computed property lacks the weak qualifier, callers will draw incorrect conclusions about the underlying semantics.
Consider:
class SomeClass {
private weak var _delegate: SomeClassDelegate?
var delegate: SomeClassDelegate? { // whoops; this should be `weak`
get { return _delegate }
set { _delegate = newValue }
}
}
And
class CustomDelegate: SomeClassDelegate { ... }
Then
let object = SomeClass()
object.delegate = CustomDelegate()
In the absence of the the weak qualifier on the computed property and without diving into the implementation details, the programmer might incorrectly conclude that the above is fine. But it’s not. Because the underlying _delegate is weak, this CustomDelegate() instance will be deallocated immediately, and the object will end up with no delegate object. And there’s no compiler warning about this behavior.
If, however, we fix SomeClass like so:
class SomeClass {
private weak var _delegate: SomeClassDelegate?
weak var delegate: SomeClassDelegate? { // great; matches underlying semantics
get { return _delegate }
set { _delegate = newValue }
}
}
Then the programmer will receive a very helpful warning:
let object = SomeClass()
object.delegate = CustomDelegate() // results in "Instance will be immediately deallocated because property 'delegate' is 'weak'"
They’ll then correctly deduce that they should keep their own strong reference to this CustomDelegate for the code to work properly.
So, bottom line, you don’t technically need the weak qualifier on the computed property that is backed by a private weak stored property, but it’s prudent to do so to avoid mysterious bugs and/or misunderstandings about the underlying semantics.
Computed properties aren't retain by ARC, so you don't need to mark it as weak.
Only one pros that I know about is to ensure that property could be nil in future. You cannot declare it as:
weak var youProperty: YourType {
get {
return _yourProperty
}
set {
_yourProperty = newValue
}
}
In Swift, if I create a delegate protocol, it can be conformed to by class and struct.
protocol MyDelegate {
// Can be conformed to by class or struct
}
The issue comes up when I declare the delegate. If the delegate is a class instance, I want the variable to be weak to avoid retain cycle. If it is a struct, there is no such need - in fact, Swift won't allow me to make the delegate variable weak. Note: I know how to create a weak delegate, but the key question is - if you create a delegate protocol that can be weak, unless you make it class-conforming only, you cannot enforce retain cycle.
class MyClass {
// Want weak var here to avoid cyclical reference
// but Swift won't allow it because MyDelegate can be
// conformed by struct as well. Dropping weak means
// cyclical reference cannot be prevented
weak var delegate: MyDelegate?
}
class MyConformingClass: MyDelegate {
}
or
struct MyConformingStruct: MyDelegate {
}
It seems like we need to declare the protocol to be for class only at all times like this because a non regular delegate protocol cannot prevent retain cycles:
protocol MyDelegate: class {
}
The fact that Swift allows you to shoot yourself in the foot this way seems to go against its design philosophy in safety.
If you really want to support a protocol on a class or struct you can always store the delegate in separate underlying variables. That way you can have one weak for when the delegate is a class. Along the lines of the following:
protocol MyDelegate {
// Can be conformed to by class or struct
}
class MyClass {
private weak var delegateFromClass: AnyObject?
private var delegateFromStruct: MyDelegate?
var delegate: MyDelegate? {
get {
return (delegateFromClass as? MyDelegate) ?? delegateFromStruct
}
set {
if newValue is AnyObject {
delegateFromClass = newValue as? AnyObject
delegateFromStruct = nil
} else {
delegateFromClass = nil
delegateFromStruct = newValue
}
}
}
}
class MyConformingClass: MyDelegate {
}
struct MyConformingStruct: MyDelegate {
}
print(" \(MyConformingClass() is AnyObject) \(MyConformingStruct() is AnyObject)")
It takes two to have a retain cycle...
If you really want to do it this way, then why not leave out the weak and just make it a strong reference. You would only have a problem if the delegate also maintained a strong reference to the object that it was delegating for.
So it becomes the duty of the delegate to make sure any reciprocal references are weak, which should be possible all of the time since MyClass is a class, and therefore you can always declare a weak reference to it.
If I have a closure that references a weak var weakSelf = self, can I change that closure to a direct function reference, through weakSelf?
struct ClosureHolder {
let closure: () -> Void
}
class ClosureSource {
func hello() {
NSLog("hello")
}
func createWeakSelfWithinInnerClosureClosureHolder() -> ClosureHolder {
weak var weakSelf = self
return ClosureHolder(closure: {
weakSelf?.hello()
})
}
func createWeakSelfDotHelloClosureHolder() -> ClosureHolder {
weak var weakSelf = self
// The code below won't compile because weakSelf is an Optional.
// Once I unwrap the optional, I no longer have a weak reference.
// return ClosureHolder(closure: weakSelf.hello)
// this strongifies the weak reference. :(
return ClosureHolder(closure: weakSelf!.hello)
}
}
Instead of createWeakSelfWithinInnerClosureClosureHolder, I'd prefer something like createWeakSelfDotHelloClosureHolder.
No you can't. Saying self.foo (if foo is a method) is exactly the same thing as to saying MyClass.foo(self). And methods curried in this fashion always keep a strong reference to the receiver object. If you want to maintain a weak reference, then you need to stick with the { weakSelf?.hello() } approach.