I have a class with a weak reference to its delegate. In a background operation, I need to set the delegate, perform an operation on the class, and then have the delegate released.
The code below works in Debug mode, but fails in Release mode, because in Release mode the delegate is released right away.
protocol DocumentDelegate:class { ... }
class MyDocument {
weak var delegate:DocumentDelegate?
func save() {
assert(self.delegate =! nil)
}
}
// Later:
// (#1) Using "var" does not work:
var delegate:DocumentDelegate? = InterimDelegate()
let document = MyDocument()
document.delegate = delegate
// Compiled in Release mode, at this time the delegate is already nil!
document.save()
delegate = nil
// (#2) Using "let" does work:
let delegate:DocumentDelegate = InterimDelegate()
let document = MyDocument()
document.delegate = delegate
// Compiled in Release mode, at this time the delegate is already nil!
document.save()
I assumed that the last instruction delegate = nil would cause the compiler to keep the delegate around until then (i.e. the "last" time the variable is used). However, thinking about it, it does make sense that the compiler optimizes the code and releases the delegate instance right away, since there are no other strong references.
However, I do not understand why the compiler does not behave the same way in the second case when using "let". Here as well the compiler could see that the delegate is not referenced via a strong reference anywhere else, but it does keep it around until the end of the block.
What would be a good way to think about this and what is a good way to keep a strong reference to the weak delegate?
While I wholeheartedly agree with Rob Napier’s analysis, for the sake of completeness, I should note that you can also make the lifetime of the object explicit:
let delegate = InterimDelegate()
withExtendedLifetime(delegate) {
let document = MyDocument()
document.delegate = delegate
document.save()
}
What you're describing is just a strong delegate. Get rid of weak, you don't mean it.
If you need an object to exist as long as you have a reference to it, and you plan to manually remove that reference at some point, that's a strong reference. The important thing for a delegate is that it at some point release its reference to avoid cycles. That's typically done with a weak reference because it makes things easy. But it can be done manually with strong reference. This is how URLSession's delegate works, for example.
If you intend the delegate to always be released after save, however, you may want to set it to nil in save. That can be nicer than having the caller do it (and matches how URLSession works; it automatically releases its delegate when it completes).
Just to explain what's happening in your code, ARC is allowed to release a reference after its last use.
// Example 1
// delegate is a strong reference
var delegate:DocumentDelegate? = InterimDelegate()
let document = MyDocument()
// Last read of delegate.
document.delegate = delegate
// delegate is released here. `document.delegate` is weak,
// so object is deallocated and set to nil.
// Compiled in Release mode, at this time the delegate is already nil!
document.save()
// This assignment is a no-op. The system was allowed to set it
// to nil earlier, so this doesn't matter.
delegate = nil
// Example 2
// This creates a strong reference
let delegate:DocumentDelegate = InterimDelegate()
let document = MyDocument()
// Last read of delegate.
document.delegate = delegate
// delegate is released here. `document.delegate` is weak,
// so object is deallocated and set to nil.
// Compiled in Release mode, at this time the delegate is already nil!
document.save()
Related
I ran into the weirdest thing, maybe someone has an explanation.
Steps:
Create a UIView A
Create a weak reference to A
Add A to the view hierarchy
Remove A from the view hierarchy
Set A to nil
The weak reference still exists.
If you skip step 3 and 4 the weak reference becomes nil as expected.
Code to test:
TestView to check deinit
class TestView: UIView {
deinit {
print("deinit")
}
}
Unit test
class RetainTests: XCTestCase {
func testRetainFails() {
let holderView = UIView()
var element: TestView? = TestView()
holderView.addSubview(element!)
element?.removeFromSuperview()
weak var weakElement = element
XCTAssertNotNil(weakElement)
// after next line `weakElement` should be nil
element = nil
// console will print "deinit"
XCTAssertNil(weakElement) // fails!
}
func testRetainPasses() {
var element: TestView? = TestView()
weak var weakElement = element
XCTAssertNotNil(weakElement)
// after next line `weakElement` should be nil
element = nil
// console will print "deinit"
XCTAssertNil(weakElement)
}
}
Both tests will print out deinit on the console, but in the case of the failing test the weakElement still holds the reference if element was in a view hierarchy for any time, although element got successfully deallocated. How can that be?
(Edit: This is inside an app, NOT a playground)
There's an autorelease attached to TestView when you add and remove it to the superview. If you make sure to drain the autorelease pool, then this test behaves as you expect:
autoreleasepool {
holderView.addSubview(element!)
element?.removeFromSuperview()
}
That said, you cannot rely on this behavior. There is no promise about when an object will be destroyed. You only know it will be after you release your last strong reference to it. There may be additional retains or autoreleases on the object. And there's no promise that deinit will ever be called, so definitely make sure not to put any mandatory logic there. It should only perform memory cleanup. (Both Mac and iOS, for slightly different reasons, never call deinit during program termination.)
In your failing test case,deinit is printed after the assertion fails. You can demonstrate this by placing breakpoints on the failing assertion and the print. This is because the autorelease pool is drained at the end of the test case.
The underlying lesson is that it is very common for balanced retain/autorelease calls to be be placed on an object that is passed to ObjC code (and UIKit is heavily ObjC). You should generally not expect UIKit objects to be destroyed before the end of the current event loop. Don't rely on that (it's not promised), but it's often true.
I have a separate class which when called upon updates the ToolTip (a text property) for an NSButton in a pistonViewController via its IBOutlet.
However, whenever I try to perform the action, I get the error
"Unexpectedly found nil while implicitly unwrapping an Optional value"
since pistonViewController.piston.tooltip didn't work, I created an instance above the class:
let pistonView = pistonViewController();
and then from within the separate class called pistonView.set_piston();
func set_piston(index: Int) {
piston1.toolTip = "yay it worked!";
}
I get the same error: found nil.
How to get the correct instance of the pistonViewController (the one that appears on viewDidLoad) so that piston1 will not be nil?
There is this solution, but it looks needlessly complex. This one appears to only work on iOS, using a storyboard.InstantiateViewController command that does not work on MacOS. This MacOS solution is poorly explained and does not appear to work.
"[How do I] Modify IBOutlet property from outside of viewDidLoad"
(But what you're really asking is how you modify a view controller's views from outside of the view controller.)
The short answer is "Don't do that." It violates the principle of encapsulation. You should treat a view controller's view properties as private, and only modify them inside the view controller's code.
(To misquote Groucho Marx: "Doc, it crashes when I do this". "Then don't do that!")
Instead, add a public property (pistonToolTip) in your PistonViewController (Class names should begin with upper-case letters).
class PistonViewController: UIViewController {
var pistonToolTip: String {
didSet {
piston?.tooltip = pistonToolTip
}
}
}
And in case you set pistonToolTip before your PistonViewController has loaded its views, add this line to viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
piston?.tooltip = pistonToolTip
// The rest of your viewDidLoad code
}
Ultimately I just set it up in viewDidLoad, with a timer waiting for the other program to get the variables that will then be assigned to the pistons.
The lack of effective pointers to instances of View Controllers makes anything else not possible or perhaps just arcane and difficult.
I have a UICollectionView in my class declared as
#IBOutlet weak var artworkCollectionView: UICollectionView!
Inside this class there is one delegate method called by two other View Controllers, one of these VC is a pop up, the other one is a normal VC.
The delegate method gets some data from the database and then updates the collection view calling inside a closure:
self.artworkCollectionView.reloadData()
When the delegate method is called by the pop up VC, then all works great. BUT when the delegate method is called by the normal VC when it gets to self.artworkCollectionView.reloadData() it gets the infamous Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value.
I have checked all the references to the cell reuseIdentifier and all is correct. I suspect that since the UICollectionView is declared as weak var, when I go from the current class to the pop up and then the pop up calls the delegate methods, the reference is not lost, but when I go from the current class to the normal VC and then the normal VC calls the delegate method the reference to my weak var is lost and so it is "seen" as nil.
#IBOutlet weak var artworkCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Set up
artworkCollectionView.dataSource = self
artworkCollectionView.delegate = self
artworkCollectionView.isUserInteractionEnabled = true
artworkCollectionView.allowsSelection = true
artworkCollectionView.register(UINib(nibName:
"MyCollectionViewCell", bundle: nil),
forCellWithReuseIdentifier: "cell")
}
// delegate method
func reloadCollections() {
retrieveAlbumRatings { (isAlbum) in
if isAlbum {
self.retrieveAlbumData(completion: { (isFinished) in
if isFinished {
// Reload collection views
self.artworkCollectionView.reloadData()
}
})
}
}
}
If I am right, my question is: how can I give weak var artworkCollectionView: UICollectionView! a STRONG reference so that it does not get lost in the flow from the current class to the normal VC and back?
EDIT: here is what I tried so far:
Remove “weak” from the outlet declaration so making it: #IBOutlet var artworkCollectionView: UICollectionView!
But I got the same error
I passed artworkCollectionView to the normal VC via override performSegue and then passed it back as an argument of the delegate method. This does not give me the fatal error but also it does not reload the UICollectionView because I think that anyway the weak reference to the UICollectionView outlet is lost.
Thanks for your help (disclaimer: I am pretty new to Swift..)
Inside this class there is one delegate method called by two other
View Controllers, one of these VC is a pop up, the other one is a
normal VC.
The delegate method gets some data from the database and then updates
the collection view calling inside a closure:
self.artworkCollectionView.reloadData()
The flow appears to be that you have a VC containing the code above, the VC can either open a pop-up or just do a standard push segue to the "normal VC".
You want some operation to occur in either the pop-up VC or normal VC, load some data and then when the user is directed back to the originating VC, the UICollectionView is updated with that data.
Your problems are the following:
I passed artworkCollectionView to the normal VC via override
performSegue and then passed it back as an argument of the delegate
method. This does not give me the fatal error but also it does not
reload the UICollectionView because I think that anyway the weak
reference to the UICollectionView outlet is lost.
You shouldn't be passing anything around like this in most cases unless you have a really good reason to do so (I don't see one).
You want a separation of concerns here. You have to think carefully about what you wanjt to pass between VCs to avoid making weird dependencies between them. I wouldn't pass outlets for multiple reasons, the first being that you now have to keep track of the outlet in multiple VCs if you ever decide to change it. The second being that it requires too much mental gymnastics to keep track of the state of the outlet since it's being passed around everywhere. The outlets are also only guaranteed to be set at certain phases of the lifecycle. For example if you retrieve the destination VC from the segue in prepareForSegue:sender: and attempt to reference the outlets at that time, they will all be nil because they haven't been set yet.
These are all good reasons why the VC that contains the code above should be the one (and the only one) maintaining control over what gets displayed in artworkCollectionView and when. The problem here is how you're approaching this, rather than having the pop-up or normal VC call the delegate method or doing weird things like passing outlets from one VC to another, just pass the data around instead.
The simplest example is:
The pop-up VC and normal VC call some code to actually fetch the
data.
Then depending on how you actually segued to the pop-up VC or
normal VC from original VC, use either parentViewController or
presentingViewController to get the reference to the original VC.
Set the data into the original VC through that reference.
Dismiss the pop-up VC or normal VC if necessary (depends on your specific app, maybe you want the user to push a UIButton to dismiss instead of doing it for them).
When the original VC comes back into view, add some code to a lifecycle method like
viewWillAppear to have it load the contents of the data into the
UICollectionView at that time.
I see no reason why you should be passing any outlets outside of the original VC that should be the one managing it.
Short answer: Don't do that. You should treat a view controller's views as private. You should add a method to your view controller that other objects call to tell it to reload it's collection view.
The longer answer is that your view controller's collection view should stick around as long as the view controller is on-screen. It sounds like you don't have a very strong understanding of object lifecycle and how ARC works. You should read up on that and do some exercises until you understand it better.
Try something like this:
//Make artworkCollectionView a normal weak var, not implicitly unwrapped.
//You'll need to change your other code to unwrap it every time you use it.
#IBOutlet weak var artworkCollectionView: UICollectionView?
...
func reloadCollections() {
retrieveAlbumRatings { (isAlbum) in
if isAlbum {
//The construct `[weak self]` below is called a capture list
self.retrieveAlbumData(completion: { [weak self] (isFinished) in
guard let weakSelf = self else {
print("self is nil");
return
}
}
if isFinished {
// Reload collection views
guard let collectionView = weakSelf.artworkCollectionView else {
print("collectionView is nil!")
return
}
collectionView.reloadData()
})
}
}
}
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.
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:
Create MapViewAnnotationDelegate
Assign it to someView.delegate
Note that there are no strong references to MapViewAnnotationDelegate (since someView.delegate is a weak reference)
Destroy MapViewAnnotationDelegate
Set someView.delegate to nil
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.
To avoid a memory leak when using NSBlockOperation in Objective-C, we would have to declare the variable as weak to be able to reference the block operation inside the block (to cancel if needed), typically like this:
__weak NSBlockOperation *blockOp = [NSBlockOperation blockOperationWithBlock:^{
if (blockOp.cancelled) {
...
}
}];
But in Swift, when I try declare my NSBlockOpeartion as weak, it is always nil.
weak var blockOp = NSBlockOperation()
Without the weak reference, all is fine except it is leaking a little bit of memory each time. How can I reference the block inside the block without leaking memory in Swift?
You can use an explicit capture list to capture an unowned reference to the operation. (This is one of the only times I'd actually suggest using unowned references, since the operation will be retained as long as its block is executing. If you're still uncomfortable with that guarantee, you could use weak instead.)
let op = NSBlockOperation()
op.addExecutionBlock { [unowned op] in
print("hi")
if op.cancelled { ... }
}
Note that this has to be split into two lines, because the variable can't be referenced from its own initial value.