Home > Articles > Programming > General Programming/Other Languages

How Best to Use Delegates and Notifications in Objective-C

The question of notifications versus delegates is a hotly debated topic in Objective-C, and often developers fall into one of the two camps. By reading this article, you will hopefully understand scenarios where each makes sense.
Like this article? We recommend

Whether you're a newcomer to Objective-C or an advanced developer, you will no doubt encounter both notifications and delegates every day. Both of these are design patterns used extensively throughout Objective-C development. They are commonplace within system frameworks such as Cocoa and Cocoa Touch.

At first glance these two distinct patterns seem to offer similar, if not the same, functionality. However, for your code to be both efficient and easy to maintain, you should employ them in different scenarios. Understanding this can save you hours of time when you're trying to untangle the code you wrote months earlier.

What are Notifications & Delegates

Notifications

Notifications provide a means of broadcasting a message from anywhere to anywhere. The NSNotification class provides this functionality in Objective-C. It is not strictly a part of the language, but rather the Foundation framework. However, you'll rarely use Objective-C without having access to Foundation. Instances of NSNotification are broadcast through an NSNotificationCenter.

Notifications contain a name, an object and a dictionary of metadata. The object and metadata are optional, but the name is required. An object can register with the notification center to receive certain notifications, filtered by name, object or both name and object. Additionally, a selector is passed, which is called when a notification matching the filter is broadcast.

An example of a notification is as follows:

// Registering as observer from one object
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(thingHappened:)
                                             name:MyThingHappened
                                           object:_myObject];

// Posting notification from another object
[[NSNotificationCenter defaultCenter] postNotificationName:MyThingHappened
                                                    object:self
                                                  userInfo:nil];

In this example one object is registering itself as an observer for the MyThingHappened notification, limiting it to when that notification occurs on the exact object, _myObject. Then, another object is posting that notification with itself as the object and nothing as the metadata dictionary, userInfo. So in this case, if the object that's posting the notification is _myObject from the context of the registering object, then the notification will cause thingHappened: to be called.

Delegates

A delegate defines an interface through which interaction between two objects can occur. In Objective-C, this is usually achieved through the use of a formal protocol using the @protocol syntax. In a delegate scenario, one object is the delegate and one the delegator. The delegator will have a reference to its delegate, through which it sends messages by calling methods defined in the delegate protocol. An example of this would be a button in a user interface which might have a delegate it notifies when it has been clicked.

The simplest example of a delegate that you'll use almost every day as an iOS developer is UITableViewDelegate. If you look up the definition for this, it defines a large number of methods, but cutting it down to just one looks like this:

@protocol UITableViewDelegate <NSObject, UIScrollViewDelegate>
@optional
- (void)tableView:(UITableView *)tableView 
        didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
@end

The table view itself has a reference to its delegate, declared as a property:

@interface UITableView : UIScrollView
@property (nonatomic, assign) id <UITableViewDelegate> delegate;
@end

This provides a way in which the table view can tell its delegate when a row has been selected, something which is likely to be interesting. The table view has a property on it that holds a reference to its delegate. When a row is selected, the table view checks to see if it has a delegate and that the delegate responds to the tableView:didSelectRowAtIndexPath: selector. If these conditions are met, then the selector is invoked. The table view must check if the delegate responds to the selector because that delegate method is marked as "optional."

Comparing & Contrasting

I don't believe there is a right and wrong answer to the question, "notification or delegate?" Sometimes it's right to use one, sometimes it's right to use the other. Below I compare and contrast various features of each and explain scenarios where each should be used.

Coupling

Notifications result in loose coupling between objects. The coupling is loose because the object sending a notification doesn't know what is listening to the notification. This loose coupling can be extremely powerful because multiple objects can all register to listen to the same notification, from different parts of an application. However, loose coupling can also make the use of notifications a nightmare to debug, since code can easily become entangled. Following the code paths produced when a notification is broadcast can become a daunting experience.

On the other hand, delegates result in tight coupling between objects. This is because the delegating object has a reference directly to its delegate. It knows if it has one and can introspect to find which delegate methods it implements, if any. The selectors that are called are defined in the protocol rather than notifications which can use any selector.

The fact that notifications and delegates provide such different coupling are an indicator that they should be used in different scenarios. If table view used notifications instead of a delegate, then all classes that use a table view could choose different method names for each notification. This would make it hard to understand code as you would need to go and find the notification registration to work out which method is called. With a delegate, it's obvious: all classes that use a table view are enforced to be structured in the same manner.

Therefore, use a delegate when it makes sense to enforce the selector that is being called. This would be scenarios where the structure of code in consumers of the delegate would benefit from being enforced. Within Cocoa development, this pattern works well for the view to view controller part of the MVC (Model-View-Controller) paradigm.

On the other hand, use a notification when you definitely don't want to couple the two sides of the notification. An example of where this would be desirable is login handling within an application. You don't want to couple all the various parts of an application that want to know about login state to the login handler.

Object Ownership

Consider your object model as a tree. An object should have just one owner, but can own multiple objects. Delegation is a way to pass a message up the tree to its owner. On the other hand, notifications are a way to message between completely separate parts of the object tree, where it would be extremely clunky to pass messages all the way up the tree to be distributed back down.

A delegate should only be used when the object being the delegate owns the object doing the delegation. A view controller owns a table view and is the delegate of that table view. For this reason you should avoid having a delegate on a singleton. It's almost never the right solution. A singleton doesn't really have an owner, or you can consider itself or the application to be its owner. One object might set itself as the delegate of a singleton, but then another might come along and break that relationship by setting itself as the singleton's delegate. The original delegate wouldn't know this had happened and would still think it was the delegate. Therefore if you're working with a singleton, avoid adding a delegate and opt for notifications instead.

Multiple Listeners

By design, notifications offer multiple listeners. There can be zero, one or many listeners for any one notification. If you are certain that you'll need multiple listeners, a notification is the correct route to go down. The instance above of login state handling is a perfect example of this. It's likely that multiple objects are going to care about login state changing, so a notification makes sense.

The standard delegate pattern allows only one delegate to be defined. However, it would be possible to provide a multiple delegation scheme by holding a set of delegates rather than just one reference. However, this is usually a bad idea as care has to be taken to ensure that retain cycles are broken. Collections in Objective-C hold strong references to their contents by default. I discourage you from trying this, though, because it is almost always the wrong pattern to use. As soon as multiple listeners are required, either you should be using notifications or you have structured your code incorrectly.

Thinking about object ownership, multiple delegates would imply multiple owners, which often leads to retain cycle issues or difficult-to-understand code.

Is the Object Known?

Sometimes you don't actually know the precise object you want to communicate with. An example of such a scenario is the keyboard in iOS, which is a view which is handled entirely by iOS for you. The keyboard comes up as required and obscures your UI. Knowing when the keyboard is being presented and when it is being hidden is therefore a common thing to care about. However, the keyboard view is entirely handled by iOS and should not be exposed, because doing so would mean apps could manipulate it, something which Apple clearly doesn't want people to do. Also, it's likely that multiple objects will care about the keyboard showing & hiding. Most view controllers will care so that they can reflow their layout to accommodate the loss in screen real estate. This is a prime example of using notifications. These are the notifications that UIKit provide for keyboard showing and hiding:

NSString *const UIKeyboardWillShowNotification;
NSString *const UIKeyboardDidShowNotification; 
NSString *const UIKeyboardWillHideNotification; 
NSString *const UIKeyboardDidHideNotification;

These notifications illustrate an important difference between delegates and notifications. Delegate methods describe exactly the information that is communicated by defining the parameters to the method. Notifications on the other hand need to use the metadata dictionary, called userInfo, to pass information. This makes them slightly clunkier to use. The keyboard notifications described above make use of this metadata dictionary to provide information such as the frames of the keyboard. However, how do you know what key each bit of information is stored as within the metadata dictionary? You need to define the keys. UIKit does this for the keyboard notifications like so:

NSString *const UIKeyboardFrameBeginUserInfoKey;
NSString *const UIKeyboardFrameEndUserInfoKey;

This adds complexity on top of a rather simple concept. In the case of keyboard notifications, this is a small price to pay for the benefit of notifications (multicast and not needing to know the precise keyboard view). However you should be sure to keep in mind this additional complexity when deciding between notifications and delegates.

Can I Use Both?

As you start to look around Apple's system frameworks, you'll often see both notifications and delegates being used for the same messages. A prime example of this is UIApplication which is a singleton holding the state of the running application. It has a delegate, called UIApplicationDelegate, which defines methods that are called as things happen such as the application going into or out of the background. However UIKit also fires notifications when each of these things happen. This is extremely useful because it's common for various parts of an application to care about the application state. A download may need to be paused when going into the background, or audio stopped playing, for example. If the application had to proxy all this through the application delegate then the code of the application delegate would become very long and complicated.

You might suggest at this point why bother having the delegate at all. The reason for having the delegate in the first place is that UIApplication needs to employ a certain feature of delegates that notifications cannot provide. This is the ability for an object to ask its delegate for information, which is passed back as the return value of a delegate method. The following UIApplicationDelegate method uses this:

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url 
  sourceApplication:(NSString *)sourceApplication 
         annotation:(id)annotation

This method is called on the delegate when the application is being requested to open a certain URL. It's the delegate's job to handle that URL if it can. If it can, it should return YES; otherwise it should return NO. The application then knows whether or not the URL has been handled. Internally, UIApplication uses this information to know whether it should try to handle it itself or not.

So in the case of UIApplication, a delegate is required anyway, therefore it makes sense to provide the flexibility to the developer of using either the notification or the delegate. Some applications will only ever use the delegate, some will use both the delegate and the notifications. You may choose to offer the same flexibility in your own design.

Summary

The question of notification versus delegate is a hotly debated topic and often developers fall into one of the two camps. I encourage you to believe in the mantra of "horses for courses." Use each where each makes sense. Hopefully, by reading this article, you understand scenarios where each has its own benefits. Now go and write more effective Objective-C!

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020