How the UITableViewDelegate and UITableViewDataSource methods get automatically called? - ios

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

Related

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.

Design Pattern behind UIKit

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.

Delegate Syntax

If I create a tableview in interface builder and connect the datasource and delegate to files owner there, do I also need to do this in the implementation of said viewcontroller?
#interface myViewController : UIViewController **<UITableViewDataSource**, **UITabBarControllerDelegate>**
ie manually specify protocol adherence?
Thanks,
When setting the delegate and datasource from interface builder there seems to be no reason to specify what protocols that class conforms to.
It works without manually specifying them because the language is pretty dynamic and this process of calling the delegate methods is done at runtime without being sure if the object does or doesn't have the required methods.
Only when setting the delegate/datasource from code there is some static type checking to see if the delegate/datasource conforms to the needed protocols.
Bottom line: write them. You get xcode autocompletion, maybe some warning in some cases, code documentation and some OCD fulfillment.
Yes. Specifying in the code that the class implements the protocols is what tells the XIB that you can make the connections and tells the compiler that all of the required methods from the protocols must be implemented (and a warning should be raised if they aren't).
Technically you can do without them, but you shouldn't.
Did you try it? Did it work without?
You're only able to connect them in interfacebuilder when you add the UITableViewDataSource and UITabBarControllerDelegate in your header file.
Just don't forget to implement the required methods (datasource & delegate) in you implementation. You'll get a warning when you do forget them btw.

Delegate ivar explanation

What exactly does this line do:
id <ViewControllerDelegate> delegate
It's always declared as an instance variable in the viewcontroller that implements the delegate protocol, don't understand what it does though.
Thanks
It means delegate is an object which implements ViewControllerDelegate protocol methods. It helps the compiler to know the methods delegate is supposed to implement.
It's useful for checking type safety at compilation time and helps with autocompletion too.
It means that any methods or properties declared in the protocol can also be handled in the delegate. Typically setting a delegate would mean that those delegate methods are called by any instances that conform to the protocol.
A table view, for example, requires you to implement a delegate, typically on 'self'. Doing so means you inherit those properties and / or methods provided in that protocol. This is how you get those magical, - (UITableView *)table... methods. That's the basic idea of it.
Also, you can take a look at this answer. Hope that helps!

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