Why use delegate and protocol instead of just passing an instance in Swift? - delegates

I was trying to pass around variables between views in Swift, and ran into the rather abstract concept of protocols and delegates.
Then I tried storing a reference to the first view in a second view and call functions on that directly. This seems to work:
SCREEN 1
class Screen1: UIViewController {
var myName = "Screen1"
override func viewDidLoad() {
super.viewDidLoad()
}
//
// checking if the segue to screen 2 is called and then passing a reference
//
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "screen2Segue"{
let vc = segue.destinationViewController as Screen2
vc.storedReference = self
}
}
func getName() -> String {
return myName
}
}
SCREEN 2
class Screen2: UIViewController {
var storedReference:Screen1!
override func viewDidLoad() {
super.viewDidLoad()
}
func testReference() {
// calling a function on the stored reference to screen 1
var str = storedReference.getName()
println("Leaving screen 2, going to " + str)
}
}
My question: what's wrong with this code? Why use delegates and protocols if you can just pass around a reference directly?
Perhaps related: when does a view get un-initialized and replaced by an entirely new view instance? Am I calling 'getName()' on an old instance?

Protocols are useful for separating implementation from interface, which helps increase code reusability, understandability, and testability.
For example, perhaps you wish to store items in a List of some sort. Some possible implementations of a List include array-based implementations and node-based (linked-list) implementations. If you were to declare a protocol called List and have classes ArrayList and LinkedList that implemented that protocol, anything that required the use of a list (variable passed as a parameter to a method, a property, etc) could use List as the variable type, and be able to function without caring about whether a the list was an ArrayList or a LinkedList. You could change which type was used, or how they were implemented, and it would not matter to whatever was using them, because only the exposed interface declared in the protocol would be visible.
Protocols can also be useful for emulating something like multiple inheritance, as a class can inherit from a superclass, as well as implement one or more interfaces. (eg. A bat is both a mammal and winged, so it could be represented as a Bat class inheriting from a Mammal class that implements the Winged protocol).
The delegate pattern uses protocols to delegate some responsibilities to another object, which is especially good for code separation and reusability. For example, the UITableViewDelegate protocol in iOS allows a UITableView to react to things like cell selection by delegating another object to handle the event. This has probably been used by millions of objects in thousands of applications, without the developers at Apple who implemented UITableView and UITableViewDelegate having ever known anything about the objects that were implementing the protocol.
By directly passing a reference between your view controllers, you are forcing the second to be completely dependent upon the first. If you ever wished to change the flow of your application so that the second view controller could be accessed from somewhere else, you would be forced to rewrite that view controller to use the new origin. If you use a protocol instead, no changes to the second view controller would have to be made.

It is a basic design principle to not expose any more of a design than you have to. By passing the reference around you are exposing the whole object. Which means that others can call any of its functions and access any of its properties. And change them. This isn't good. Besides letting others use the object in ways it might not have intended, you will also run into issues if you try to change the object in the future and find out that it breaks somebody else who was using something you didn't intend. So, always a good idea to not expose anything that you don't have to. This is the purpose of delegates and protocols. It gives the object complete control over what is exposed. Much safer. Better design.

I think you didn't fully get the understanding what protocols are.
I always say protocols are like contracts.
The delegate object that implements a certain protocols promises that it can do things the delegator can't do.
In real world I have a problem with my house's tubes.
I (the delegator) call a plumber (the delegate) to fix it. The plumber promises (by contract) to be able to duo it. The promise is the protocol. I don't care how he do it, as long as he does it.
But these contracts are not only useful for delegation.
I am just writing a food ordering app. As it has a menu it need item to display in it.
I could go with basic inheritance and write a class MenuItem, that all sub classes must inherit from.
Or I write an protocol to express: «No matter what object you are, as long as you fulfill this contract we have a deal». this allows me to create many different classes or annotate existing classes in categories, although I don't have the tool of multiple inheritance.
Actually I do both: I write a protocol MenuItem and a class MenuItem that conforms to the protocol. Now I can use simple inheritance or use classes that do not inherit from the class MenuItem.
Code in Objective-C (sorry: I am still transitioning to Swift)
#protocol MenuItem <NSObject>
-(NSString *)name;
-(double) price;
-(UIColor *)itemColor;
#end
#interface MenuItem : NSObject <MenuItem>
#property (nonatomic, copy) NSString *name;
#property (nonatomic, assign) double price;
#property (nonatomic, strong) UIColor *itemColor;
#end
#import "MenuItem.h"
#implementation MenuItem
-(id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if (self) {
self.name = [decoder decodeObjectForKey:#"name"];
self.price = [decoder decodeDoubleForKey:#"price"];
self.itemColor = [decoder decodeObjectForKey:#"itemColor"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeDouble:self.price forKey:#"price"];
[encoder encodeObject:self.name forKey:#"name"];
[encoder encodeObject:self.itemColor forKey:#"itemColor"];
}
#end
Apple uses the same Architecture for NSObject: there is a protocol and a class NSObject. This allows classes, that aren't intact inheriting from the class NSObject to act ash an NSObject. One famous example:NSProxy.
in your case Screen1 promises to be able to understand messages that are send by the detail view controller Screen2. These allows decoupling: any object that does understand Screen1's protocol can be used. Also it helps to maintain a sane object tree, as we don't have to have circular imports. But in general you have to keep in mind that the delegator (Screen2) must keep a weak reference to it's delegate, otherwise we have a retain circle.
Of course an important example it UITableView:
The table view object knows everything about rendering it's cells, handling scrolling and so one. But the engineer who wrote it couldn't now how you want your table view look like. That's why he introduced a delegate to give you the chance to create the right cell. As he couldn't also know what your data looks like, he also introduced the datasource - that works exactly like a delegate: you will be asked to provide all information about your data, that are needed.

This is mostly a matter of opinion so this question should probably be closed, but I think the developer community as a whole is in an agreement on this so I am going to answer it anyway.
An important concept in Software Architecture (the design of the structure of code) is called Separation of Concerns. The basic principle is that you should break down what your code has to do into small components that only have one distinct purpose. Each of these components should be able to stand mostly on their own without much concern with other components other than the ones it needs to directly be interacting with.
This helps greatly with code reuse. If you design a small component that is independent of most / if not all other components, you can easily plug that into other parts of your code or other applications. Take UITableView for example. By using the delegate pattern, every developer can easily create a table view and populate it with whatever data they want. Since that data source is a separate object (with the separate concern of coming up with the data) you can attach that same data source to multiple table views. Think of a contact list on iOS. You will want to access that same data in many ways. Instead of always rewriting a table view that loads the specific data and displays it in a specific way, you can reuse the data source with a different table view as many times as you want.
This also helps with the understandability of your code. It is tough for developers to keep too many thing in their head about the state of your app. If each of your code components are broken down into small, well defined responsibilities, a developer can understand each component separately. They can also look at a component, and make accurate assumptions about what it does without having to look at the specific implementation. This isn't such a big deal with small apps, but as code bases grow, this becomes very important.
By passing in a reference to your first view controller, you are making your second view controller completely dependent on the first. You cannot reuse the second view controller in another instance and its job becomes less clear.
There are lots of other benefits to separation of concerns but I believe those are two compelling and important ones.

I think the problem with the latter arises with multiple reuse of a single class.
Take for example a custom UITableViewCell called CustomTableViewCell. Let's say you have Class A and Class B which both have tableViews and both would want to use CustomTableViewCell as their cell. You now have two options. Would you rather:
A. Use a delegate/protocol for CustomTableViewCell called CustomTableViewCellDelegate. Declare a single object inside the class CustomTableViewCell named "delegate" which implements the mentioned protocol and call on that regardless of what class it calls on
or
B. Declare an object for each class (Class A, Class B) inside CustomTableViewCell so you can hold a reference to each of them.
If you need to use CustomTableViewCell for a number of classes, then I think you know which option to take. Declaring multiple objects for different classes inside CustomTableViewCell would be a pain to see from a software architecture standpoint.

Related

What is the purpose of protocols if all methods are optional?

I understand what purpose protocols serve (to have a type conform to a set list of methods or/and properties), but I don't understand what the purpose is of a protocol with all optional methods. One example would be UITextFieldDelegate.
If all methods are optional in a protocol, why would you conform to the protocol instead of just writing the methods from scratch in your class? I don't see what the benefit or purpose of conforming to the protocol is in this case.
Are the optional methods there just as suggestions of functionality that could be implemented?
Historically, for delegates and data sources in Cocoa, informal protocols were used. Informal protocol was implemented trough a category for NSObject class:
#interface NSObject (NSTableViewDelegate)
- (int)numberOfRowsInTableView:(NSTableView *)tableView;
// ...
#end
Later, optional methods in protocols were introduced. This change leads to better documenting of class responsibilities. If you see in code, that class conforms to NSTableViewDelegate, you suspect that somewhere exists a table view, that managed by instance of this class.
Also, this change leads to stronger checks in compile time. If programmer accidentally assign wrong object to delegate or dataSource properties, compiler will warn.
But your assumption is also correct. Optional methods are also suggestions for possible functionality.
By default, all methods in a protocol are required. Each method has to be marks as optional if the nor required for everything to function correctly.
If all methods are optional in a protocol, why would you conform to the protocol instead of just writing the functions from scratch in your class?
Conforming to a protocol allow your class to tell another object the methods it has without the other object needing to know about your class. This is really useful when using Delegation as it allows the delegate to decide what information they wish to receive/provide to another class.
For example,the UIScrollViewDelegate protocol only defines optional methods. Lets say we have a class Foo that we want to know when things change with a UIScrollView.
If we decided to throw that protocol away and implement the functions from scratch, how would we tell UIScrollView which methods we implement and which methods to call when certain event occur? There is no good way it could find out. When UIScrollView was built, it didn't know about Foo so it can't know what methods it implements. Also, Foo has no way of knowing what methods can be called on it by the UIScrollView.
However, when UIScrollView was built, it did know about UIScrollViewDelegate. So if Foo conforms the the UIScrollViewDelegate protocol, there is now a common definition that both Foo and UIScrollView can follow. So Foo can implement any methods it cares about, like scrollViewDidScroll: and the UIScrollView just needs to check if the delegate implemented the methods in UIScrollViewDelegate.
The protocol establishes a contract for the interface between one object and another. The fact that the methods are optional simply says that you don't have to implement that particular method, but you can if your app calls for it.
Generally, if you're conforming to a protocol for which all of the methods are optional, though, you're doing that for a reason, namely that you plan on implementing one or more of those methods. Just because all of the protocol's methods are optional doesn't mean you will not implement any of them, but rather simply that you can elect which are relevant in your particular situation.
For example, consider the UITextFieldDelegate protocol. You'd generally conform to that because you want to specify, for example, whether certain characters should be allowed to be inserted into the text field or what to do when the return key is pressed. Sometimes you only want to implement the former. Sometimes you only want to implement the latter. Sometimes you do both. But just because you choose to implement one or the other doesn't mean you necessarily want to do other one (but you can if you want). Frankly, though, if you really didn't want to implement any of the methods, you probably wouldn't even bother to specify the delegate of the text field, nor bother to specify that you're conforming to the protocol.
Bottom line, the protocol that consists solely of optional methods basically says "if you need it, this is the documented interface for the methods you may elect to implement". The protocol still is very useful to establish the possible interfaces, but doesn't force you to implement those methods you do not need.

Cocoa app passing objects between controllers

I am in the process of building a Cocoa app, which is comprised of a window divided in 3 sections. Each section is responsible for its own business and there are around 30 controls in it between table views, pop up buttons etc.
I started with a single Controller but things get messy pretty easily, so I decided to break the logic down in 3 controllers object (one each section of the view). I then created the NSObject reference on Interface Builder and hooked up all the outlets, actions, data sources and delegates. So far so good.
Now, the three sections pass objects to each other and therefore I need a way to set an object from one class to another. The object in question is a class variable, but as I have no reference to the object I don't know how to pass it around.
Is there a way to do this or is this just the wrong approach overall?
Solution:
As Sergio mentioned below in one of the comments, the solution seems to be to create a weak reference to the other controllers inside each controller as IBOutlet and then in the Xcode Interface Builder link the controller objects together. As a result, now each controller can access the exposed methods and variables of the referenced controllers.
Now, the three sections pass objects to each other and therefor I need a way to set an object from one class to another. The object in question is a class variable, but as I have no reference to the object I don't know how to pass it around.
What seems missing in your design is a Model (as in Model-View-Controller). This would be a class encapsulating all the state of your app, even if it is transitory state, so that each affected object have access to it.
One easy implementation for such a model class is a singleton, so that it is readily available in all of your controllers. Have a look here for some thought about the implementation of a singleton in Objective-C.
Once you have your model class, your controllers could access it like this, e.g.:
[MyModel sharedModel].myObject = ...;
This approach is good, IMO, if it makes sense for you to go in the direction of creating a Model for your design. This depends on the semantics of the object that your controllers share. So, there might be alternative solutions better fit for your case. E.g., one controller could be the owner of the shared object, and the other two could receive a reference to the first controller on init so that they can access its public properties.

Cocoa lazy instantiation - best practice

I have a question about the best coding practice for lazy instantiation. 
I have a custom class (MainClass) that consitutes the model of my view controller. One of the properties of MainClass is another custom class (SubClass).
Now let's say I want to acces and set some of the properties of SubClass from my view controller.
Should I lazy instantiate SubClass in MainClass?
Lazy instantiating SubClass in MainClass save me the trouble to check the existence of SubClass (and to create it if it doesn't exist) every time I want to set one of its properties.
On the other hand though I lose the ability to set variables in my views only if SubClass exists. Let me explain better. Let's say I want to set the stringValue of my textfield only if SubClass.name exists. Every time I ask for the existence of SubClass.name the MainClass will lazily instantiate SubClass which is a waste.
What's the best way to proceed?
You need to make up your mind about the aesthetics, if that's what's driving this question, or you need to explain the performance constraints.
Yes, lazy initialization has advantages and disadvantages.
ADVANTAGES
you don't pay for objects you never use
you don't need actually set fields on the object you won't ever use
if you need it, you can build the object at the last minute, which is usually preferable to building it at startup
DISADVANTAGES
(slight) complexity -- especially if you or colleagues aren't accustomed to the idiom
if you forget to call Initialize() or equivalent in an accessor, you may get tricky bugs in some languages, or crashes in others
A hybrid approach is possible. For important tasks, use lazy instantiation:
- (void) display {
[self initialize];
[self display];
}
and for unimportant tasks, simply check for initialization.
- (void) updateCaches {
if ([self isInitialized]) {
[self reloadCachedDataFrom: [self startDatabaseSession]];
}
}
You don't want to build your object just to update its caches, but perhaps, if the object is live, you would like to go ahead and keep the caches warm. So, you see if you've already instantiated the object, and reload the caches only if it already has been set up.

Understanding and Reproducing the KVC Hillegass Way to Insert/Remove Objects in/from Controllers

In Aaron Hillegass' Cocoa Programming for Mac OS X, the Raiseman application connects a button in Interface Builder (IB) to an NSArrayController with sent action -remove:. In the MyDocument class he implements two KVC methods:
- (void)insertObject:(Person *)p inEmployeesAtIndex:(int)index;
- (void)removeObjectFromEmployeesAtIndex:(int)index;
When this button is pressed, the -removeObjectFromEmployeesAtIndex: method is called and the currently selected Person (Model) object is removed from the array.
How does the remove: method used in IB cause the -removeObjectFromEmployeesAtIndex: method to be called?
How do I reproduce this effect with an NSTreeController?
If you want a simple built-in option, then it's only going to create an instance of the class you specified in IB. To create another instance, you're going to need to code it yourself. You should have all the information you need from the Tree Controller to insert the new class into the proper place in the hierarchy. Some diligent searching should give you the code you need.
To attempt to help you understand how the NSArrayController mechanism works, I'll explain the best I can from my knowledge of Objective-C and the runtime. Objective-C is a very dynamic language, and you can dynamically call selectors (methods). Since the NSArrayController knows the name of your class (e.g. "Employee"), its internal implementation probably looks something like the following (or easily could):
NSString *removeSelectorName = [NSString stringWithFormat:#"removeObjectFrom%#sAtIndex:",
self.objectClassName];
SEL removeSelector = NSSelectorFromString(removeSelectorName);
[dataRepresentation performSelector:removeSelector
withObject:[NSNumber numberWithInt:self.selectionIndex];
There are examples of this elsewhere in KVO, as with the +keyPathsForValuesAffecting<Key> method (documentation here), which describes which keys cause another key to be updated. If your key is named fullName and it updates whenever the first or last name changes, you would implement this in your class:
+ (NSSet *)keyPathsForValuesAffectingFullName {
return [NSSet setWithObjects:
#"firstName",
#"lastName",
nil];
}
Further searching (and this question) turned up this documentation page, which explains the semantics of how that method gets called.

Need some tips regarding the Cocoa MVC/KVO patterns

This is a very wide-ranging/vague question, but here goes. Apologies in advance.
The app (desktop app) I'm building takes different kinds of input to generate a QR code (I'm just building it to learn some Obj-C/Cocoa). The user can switch between different views that allow input of plain text (single text field), VCard/MeCard data (multiple text fields), and other stuff. No matter the input, the result is a QR code.
To keep things contained, I'd like to use the views as view-controllers, so they handle they're own inputs, and can simply "send" a generic "data to encode" object containing all the data to a central encoder. I.e. the plain text view would make a data object with its textfield's text, while the VCard/MeCard view would use all of its fields to make structured VCard/MeCard data.
I can bind all of this stuff together manually in code, but I'd really like to learn how bindings/KVO could help me out. Alas, after reading Apple's developer docs, and the simpler tutorials/examples I could find, I'm still not sure how to apply it to my app.
For instance: The user edits the textfields in the VCard-view. The VCard view-controller is notified of each update and "recalculates" the data object. The central encoder controller is then notified of the updated data object, and encodes the data.
The point of all this, is that the input views can be created completely independently, and can contain all kinds of input fields. They then handle their own inputs, and "return" a generic data object, which the encoder can use. Internally, the views observe their inputs to update the data object, and externally the encoder needs only observe the data object.
Trouble is I have no idea how to make this all happen and keep it decoupled. Should there be an object controller between the input-view and its fields? Should there be another one between the view and the encoder? What do I need where? If anyone has a link to a good tutorial, please share.
Again, I can roll my own system of notifications and glue code, but I think the point is to avoid that.
Definitely a vague question, but one beginner to another, I feel your pain :)
I downloaded and unpacked every single example and grep through them frequently. I've found that to be the most valuable thing to get me over the hump. I definitely recommend not giving up on the examples. I hacked up this script to download and unpack them all.
In terms of good KVO patterns, I found the technique described here to be very useful. It doesn't work as-is in Objective-C 2.0 however. Also he doesn't give much detail on how it's actually used. Here's what I've got working:
The KVODispatcher.h like this:
#import <Foundation/Foundation.h>
#interface KVODispatcher : NSObject {
id owner;
}
#property (nonatomic, retain) id owner;
- (id) initWithOwner:(id)owner;
- (void)startObserving:(id)object keyPath:(NSString*)keyPath
options:(NSKeyValueObservingOptions)options
selector:(SEL)sel;
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context;
#end
And the KVODispatcher.m is as so:
#import "KVODispatcher.h"
#import <objc/runtime.h>
#implementation KVODispatcher
#synthesize owner;
- (id)initWithOwner:(id)theOwner
{
self = [super init];
if (self != nil) {
self.owner = theOwner;
}
return self;
}
- (void)startObserving:(id)object
keyPath:(NSString*)keyPath
options:(NSKeyValueObservingOptions)options
selector:(SEL)sel
{
// here is the actual KVO registration
[object addObserver:self forKeyPath:keyPath options:options context:sel];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
// The event is delegated back to the owner
// It is assumed the method identified by the selector takes
// three parameters 'keyPath:object:change:'
objc_msgSend(owner, (SEL)context, keyPath, object, change);
// As noted, a variation of this technique could be
// to expand the data passed in to 'initWithOwner' and
// have that data passed to the selected method here.
}
#end
Then you can register to observe events like so:
KVODispatcher* dispatcher = [[KVODispatcher alloc] initWithOwner:self];
[dispatcher startObserving:theObject
keyPath:#"thePath"
options:NSKeyValueChangeNewKey
selector:#selector(doSomething:object:change:)];
And in the same object that executed the above, you can have a method like so:
- (void) doSomething:(NSString *)keyPath
object:(id)object
change:(NSDictionary *)change {
// do your thing
}
You can have as many of these "doSomething" type methods as you like. Just as long as they use the same parameters (keyPath:object:change:) it will work out. With one dispatcher per object that wishes to receive any number of notifications about changes in any number of objects.
What I like about it:
You can only have one observeValueForKeyPath per class, but you may want to observe several things. Natural next thought is "hey maybe I can pass a selector"
Oh, but it isn't possible to pass multiple arguments via performSelector unless wrapper objects like NSNotification are used. Who wants to clean up wrapper objects.
Overriding observeValueForKeyPath when a superclass also uses KVO makes any generic approaches hard -- you have to know which notifications to pass to the super class and which to keep.
Who wants to re-implement the same generic selector-based observeValueForKeyPath in every object anyway? Better to just do it once and reuse it.
A nice variation might be to add another field like id additionalContext to KVODispatcher and have that additionalContext object passed in the objc_msgSend call. Could be useful to use it to stash a UI object that needs to get updated when the observed data changes. Even perhaps an NSArray.

Resources