Swift UITableView delegate and dataSource declaration and save loops

As far as I understood, to use the delegate template in swift I had to declare the property as follows:

weak var delegate: TheDelegateProtocol! 

And such a protocol:

 @class_protocol protocol TheDelegateProtocol { } 

To avoid loop hold and stick to what we use in object C.

Now, if I look at what they have in the UITableView definition, I only see:

 var dataSource: UITableViewDataSource! var delegate: UITableViewDelegate! 

and

 protocol UITableViewDelegate : NSObjectProtocol, UIScrollViewDelegate { [...] } 

I assume that this is due to the fact that these are only bindings to Objective-C, and an objective definition of C may take precedence over a quick definition, but I cannot find an official explanation in the documentation.

+3
source share
1 answer

This is for the same reason that, in general, many Cocoa delegates are not weak. Large parts of Cocoa are not recorded using ARC - because they precede it. They manage memory manually, as we used to do in the good old days. Thus, they do not enjoy the ARC weak (which means weak here). They use the clean, non-memory-driven assignment of delegates (and data sources). They do not save it, so there is no save cycle; but since they do not use ARC, they are not protected from failures.

Thus, you are responsible for ensuring that such a delegate does not die during the life of the primary instance, so that he does not try to send a message to a dangling pointer and a failure.

You can see this by experiment (this is Objective-C, but you can easily see the point):

 self->_obj = [NSObject new]; nav.delegate = self->_obj // nav is our navigation controller, the root view controller dispatch_async(dispatch_get_main_queue(), ^{ // cry havoc, and let slip the dogs of war! self->_obj = nil; // releases obj - now what is nav.delegate pointing to?? NSLog(@"Nav Controller delegate: %@", ((UINavigationController*)self.window.rootViewController).delegate); // if you're lucky it might print something! // or more likely it will just crash, or maybe print and *then* crash }); 

A crash like this is exactly what prevents the ARC-weak because it automatically replaces the drop-down pointer with nil - and the noil message in Objective-C is harmless.

+3
source

Source: https://habr.com/ru/post/979030/


All Articles