Design Pattern behind UIKit - ios

I recently started working with iOS applications. I could see that, many of the off-the-shelf objects provided by the UIKit uses delegate pattern. For example, a UITableView has a datasource and a delegate for it to provide with data and other other table view functionality.
So, is the underlying design pattern behind this delegate pattern, strategy design pattern? The reason in favor to me is that, in strategy pattern, the delegating object has a reference to a delegate which confirms to a particular interface.
So lets say, I have a class MyDataSource which confirms to the protocol / interface UITableViewDataSource and I implement the behaviors in MyDataSource. And I pass an instance of MyDataSource to UITableView. This is what we do in strategy pattern. So is my understanding right?

What you are referring to is a Cocoa/CocoaTouch design pattern called delegation. I think your understanding is very accurate, however in the example you give at the end of your post it would most likely be the UITableView sending a message to the MyDataSource object and passing itself in as one of the protocol method arguments.
An example would be something like -
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
The above method is implemented by the delegate object and would implement its own strategy. The collectionView that calls this method is passed in as one of the arguments.
Also the UITableView must have a way of accessing MyDataSource object. This is achieved by setting the delegate/dataSource property. It is usually of type id and is weak referenced.
Please view this SO post for more info about the strategy pattern being synonymous to delegation.

Related

Dissect an iOS protocol programmatically, then invoke those methods?

The question (reflection or something like it?)
Is it possible (in Swift) to extract all the method signatures of an iOS protocol programmatically, such as for UITextViewDelegate, whose methods are all optional, without having to instantiate a separate class that explicitly implements all the protocol's methods?
In this case, want to intervene as the delegate to intercept one of the methods and do some related operation to that activity, then daisy chain the delegate call forward. But unfortunately, becoming the delegate entails responsibility to forward all of the protocol the downstream consumer
If you're saying what I think you're saying, there actually is a very simple way to do this: implement forwardingTarget(for:), as I do here:
https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch12p611tabBarMore/ch25p882tabBarMore/MyDataSource.swift
The idea is that I don't know what the table view's dataSource actually does, because the table view and its data source belong to Cocoa, but I want to act as a "man in the middle" between them and just tweak the behavior of one data source method if it is called. All other method calls just get passed along, without my even knowing what they are.

Why do we need to override methods — Objective-C?

I'm new to Objective-C and I did a big step from web developing (php) to ios developing.
Why should I override and implement methods from the superclass? Don't these methods already exist in their superclass?
For example, I have a table view controller. Why isn't a property like: numbers of rows, Instead of implementing a method? And why don't we implement all the methods that exist in the superclass?
I guess I have a lack of knowledge in all of the inheritance system in Objective-C.
Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. The implementation in the subclass overrides (replaces) the implementation in the superclass by providing a method that has same name, same parameters or signature, and same return type as the method in the parent class. The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed.
This is a very powerfull aspect of the object oriented programing.
Exemple:
C subclass B and B subclass A
They all have the same methode print
If you have an Arrays with one instance name arr
For i in arr {
Print (i)
}
The good methode print 'll be call for each object
You are talking about overriding methods but the example you gave with the tableView is not overriding the methods. The tableView is using the delegate pattern. In the delegate pattern, there is a protocol that is defined. Let's use UITableView as the example:
The protocol that is defined is the UITableviewDataSource. This is basically a declaration that methods like numberOfRowsInSection should exist in whichever class conforms to this protocol.
When you tell the tableView that you conform to its UITableViewDataSource protocol by saying tableview.dataSource = self, you are telling it that you implement the methods listed in the UITableviewDataSource declaration.
This pattern creates an api for the tableView to consume without having knowledge of the class providing it. Essentially, the tableview will be asking your class for information via the UITableviewDataSource api that was defined.
You can do a search on the delegate pattern to find the pros and cons of implementing it.

How the UITableViewDelegate and UITableViewDataSource methods get automatically called?

Just conforming to the datasource and delegate protocol and assigning the delegate and data source object in my class implementation file and defining the methods defined under the datasource and delegate protocol is all anyone need?How does those methods get called automatically?
It's just a kind of design pattern, which expose to you as many methods as needed to give you enough flexibility to control it and hide from you all the hard work.
Since you're assigning self to delegate and datasource properties, that mechanism is just calling those exposed protocol method on object which is the "self". Those methods are called while it's building up dynamic content, while reloading, etc.
If you're interested with implementation, you could check this open class with the same design pattern:
iCarousel

Is dataSource of UITableView exactly a delegate design pattern like the table information provider delegate?

A UITableView object has two properties: one delegate, and one dataSource. Are they exactly the same design pattern? I don't see books or reference calling dataSource a second delegate for the UITableView.
No, they are not the same thing but they are using the delegate pattern.
They are both different and distinct delegates that serve different purposes. One property is for the UITableViewDataSource and the other is for UITableViewDelegate.
Here is how they are defined in UITableView.h:
#property(nonatomic, assign) id<UITableViewDataSource> dataSource
#property(nonatomic, assign) id<UITableViewDelegate> delegate
The delegate pattern is pretty simple and the Wikipedia entry sums it up pretty well:
In software engineering, the delegation pattern is a design pattern in
object-oriented programming where an object, instead of performing one
of its stated tasks, delegates that task to an associated helper
object. There is an Inversion of Responsibility in which a helper
object, known as a delegate, is given the responsibility to execute a
task for the delegator. The delegation pattern is one of the
fundamental abstraction patterns that underlie other software patterns
such as composition (also referred to as aggregation), mixins and
aspects.

What is the purpose of an iOS delegate?

I understand what a delegate does in iOS, and I've looked at sample code, but I'm just wondering about the advantages of this type of encapsulation (as opposed to including delegate methods in the primary object).
The advantage of the delegate design pattern is loose coupling. It enables class A (the delegate) to depend on class B (the delegating class) without class B having to have any knowledge of class A. This ensures that the dependency relationship is one-way only, rather than being circular.
It also forms the foundation (lower case "f") of Apple's frameworks because it allows them to invoke your code as appropriate when functionality specific to your application is required. For example, responding to a button tap or telling a table view how many sections there should be.
Delegation is a design pattern not only used in iOS but many other languages. It enables you to hand values and messages over in your class hierarchy.
In iOS, delegation requires the "delegate" class to implement a protocol which contain methods that the "delegating" knows about. Still following?
The delegating class's implementation will call these protocol methods, but the delegate class will implement these methods in their class.
This keeps your Classes clean.
In reality, you don't really need delegation if you can add new methods to a single class. But for UIKIT's UIView class, Apple will not allow you to add new implementations to their class.
correct me if I'm wrong.
The most common use of a delegate in iOS is to establish communication within modules that are unrelated or partially related to each other. For example, passing data forward in a UINavigationController is very easy, we can just use segue. However, sending data backwards is little tricky. In this case, we can use delegate to send the data backward.
Let's call, the class, associated with the first Controller ClassA and the class, associated with the second Controller ClassB. The first Controller is connected to the second controller with a forward segue. We can pass data from ClassA to ClassB through this segue. Now, we need to pass some data to ClassA from ClassB for which we can use delegates.
The sender class(ClassB) needs to have a protocol in its header file(.h) and also a reference of it as delegate inside the block, #interface ClassB .... #end. This reference let's the ClassB know that it has a delegate. Any class that wants to use this ClassB will have to implement all of this protocol's required methods(if any). So, the receiver class,ClassA will implement the method but the call will be made by the sender class, ClassB.
This way, receiver class doesn't need to worry about the sender class' internal structure, and can receive the required information.
Delegation as I understand it is when an object will pass the responsibility of handeling an event to another object thus "delegating" the responsibility to that object.
For example if you have an NSButton in iOs you generally assign the Delegate to be the parent view controller. This means instead of handeling touchUp events in the definition of the button it is instead handled in the view controller.
The main advantage of delegation over simply implementing methods in the "primary object" (by which I assume you mean the object doing the delegating) is that delegation takes advantage of dynamic binding. At compile time, the class of the delegate object does not need to be known. For example, you might have a class that delegates the windowDidMove: method. In this class, you'd probably see some bit of code like
if([[self delegate] respondsToSelector:#selector(windowDidMove:)]) {
[[self delegate] windowDidMove:notification];
}
Here, the delegating class is checking at runtime whether its delegate responds to the given method selector. This illustrates a powerful concept: the delegating class doesn't need to know anything about the delegate other than whether it responds to certain methods. This is a powerful form of encapsulation, and it is arguably more flexible than the superclass-subclass relationship, since the delegator and the delegate are so loosely coupled. It is also preferable to simply implementing methods in the "primary object" (delegating object), since it allows runtime alteration of the method's implementation. It's also arguable that this dynamic runtime makes code inherently more dangerous.
Delegate is an important design pattern for iOS app.All apps directly or behind the hood use this delegate pattern.
Delegate design pattern allows an object to act on behalf of another.
If we are working with tableview then there are "tableViewDelegate" and "tableViewDataSource". But what this means
Suppose you have a tableview.
now some major concern for this.
1.what is the datasource(the data that will appear in table view) for this tableview?
2.How many row for table view etc.
delegate design pattern solve these question using another object as the provider or the solver of these question.
An object mark himself to the table view and ensure the table view that "Yes i am the man who can assist you" by marking himself as the delegate to the table view .Thanks
The class marked as delegate takes the responsibilities to handle the callbacks sent while some event occurs. For example, in case of UITextField, there are some methods called when some events occurs like editing started, editing ended, character typed etc. These methods will already be defined in the protocol. We will have to assign delegate for that i.e. which class is going to handle these events.
With the help of a delegate, two-way communication can be achieved. A delegate might be used to make an object reusable, to provide a flexible way to send messages, or to implement customization.
In iOS ecosystem especially UIKit Framework which consists of UIApplication, UITableView, UICollectionView, UITextfield & so on uses delegate & datasource design pattern intensively to communicate data to and fro.
Delegate design pattern is used to pass/communicate data from FirstVC(Delegator) to SecondVC(Delegate) to complete a task.
Here, SecondVC(Delegate) conforms to a protocol delegate & implements all its requirements like methods by providing body to complete that task given by FirstVC(Delegator).
Also, FirstVC(Delegator) object will be having a optional property of protocol delegate type i.e delegate which must be assigned by SecondVC(Delegate).
Now, FirstVC(Delegator) can call that method residing in SecondVC(Delegate) by passing data from its delegate property.
EX: CEO(FirstVC) which passes data i.e "confidential data" to Secretary(SecondVC) to do further processes using that data.
Datasource design pattern is part of Delegate pattern which is used to pass/communicate data from SecondVC(Delegate) to FirstVC(Delegator) when a task is assigned to SecondVC(Delegate).
Here, SecondVC(Delegate) conforms to a protocol datasource & implements all its requirements like methods with return type by providing body to talk back to FirstVC(Delegator) after the task is given by FirstVC(Delegator).
Also, FirstVC(Delegator) object will be having an optional property of protocol dataSource type i.e dataSource which must be assigned by SecondVC(Delegate).
Now, FirstVC(Delegator) can call that method with a return type residing in SecondVC(Delegate) by passing data from its dataSource property.
EX: Secretary(SecondVC) replies back with a data i.e "Sir, I am already having too much work to do. Please, can you assign that data to others" to CEO(FirstVC). Now, CEO(FirstVC) will analyse that data to do further processes.
Delegation means one object passes behaviour to another object..

Resources