Welcome!

Microsoft Cloud Authors: Janakiram MSV, Yeshim Deniz, David H Deans, Andreas Grabner, Stackify Blog

Related Topics: Microsoft Cloud

Microsoft Cloud: Article

Cocoa - Exploring the Delegate Design Pattern

When I first started learning Cocoa I ran across a design pattern that I had seen implemented a few times before

Kevin Hoffman's Blog

When I first started learning Cocoa I ran across a design pattern that I had seen implemented a few times before but I had yet to see it labelled with a name. This pattern is called the Delegate design pattern. Coming from C#, I found this initially confusing because in C# the concept of a delegate is slightly different than the concept of a delegate in the Cocoa world. In C#, a delegate is essentially a function pointer, and when someone in Cocoa refers to a delegate, they are referring to an entire instance of a class to which work is delegated.

To see how this pattern works, I needed an example. So, the example I used was a control that is bound to an array of items. So, let's say you have a control that you want to render a list of customers. There are two really obvious approaches to this problem: data binding and the Delegate design pattern.

In data binding, the idea is that your controller will "stuff" the data into the view in some fashion. Often this involves cramming the entire result set into the view and letting the view deal with things like scrolling or paging. You can almost think of the Delegate design pattern as reverse data binding - the control asks the controller for the data it needs, and only the data it needs. The benefits here are that in some data binding scenarios, it becomes extremely easy to tie the view too closely to the controller - making it difficult to use the view for anything but a specific type of data. In addition, if you're not using something like the delegate design pattern, it also becomes easy to get inefficient and cram immense result sets into the control when you really only need to be working with a small window into the result set at any given time.

So, let's take a look at a quick sample. Assume that you're building a custom view in Cocoa called RadialLayoutView. This view lays out all of its subviews so that they are all arranged in a circle. Each of the subviews is actually a piece of data with a name and description. You could easily (especially if you're coming from the WPF world) data bind the control to an array of a custom type, say RadialNode or something. However, there is a way to make it so that your control only ever has to worry about those nodes that are on the screen at a given time, and it doesn't need to know anything about the underlying model that is supplying the name and description values.

The delegate is going to be a pointer to an object that will do the work required of the delegate. In this case, we're going to want to make a delegate that will provide the control with the count of all nodes in the system, and it will also provide the name and description of a single node. Whenever the control needs an item, it can simply ask the delegate for one. This provides a huge amount of power and flexibility and loose coupling between the view and the model that you don't normally find in standard databinding patterns.

To tell the application what the control demands of its delegate, we can use a protocol:

@protocol RadialLayoutDelegate
@required
  - (unsigned) countNodes;
  - (void) nodeAtIndex: (unsigned)index
                        name: (NSString **)
outName
                 description: (NSString **)
outDescription;
@end

Yes, there's some Leopard syntax here, but it's stuff that you can find elsewhere so there's no NDA problem. With the protocol in mind, we can define (in the .h file) our custom view as:

@interface RadialLayoutView
{
     IBOutlet id<RadialLayoutDelegate> delegate;
}
@end

You may notice some similarity between .NET Interfaces and Cocoa protocols. That, of course, is because they both serve the same purpose - they define a set of constraints to which any object implementing said interface (or protocol) must conform. The difference is that you can have pieces of a protocol be optional using the @optional keyword, whereas in .NET if you implement an interface, you must implement all of it or suffer the consequences.

Now, I can write code inside the custom view that just invokes methods on the delegate in order to get the data it needs in order to create and render its list of subviews. For example, to get the name and description of the root node in the data set:

NSString *rootName;
NSString *rootDescription;

[delegate nodeAtIndex:0 name:&rootName
description:&rootDescription];

That's all there is to it. The nodeAtIndex method coupled with the countNodes method are all that's needed to give the control the ability to render a near-infinite amount of data because it doesn't have to maintain it all at once, and the delegate can be fetching that data from XML, from memory, or from Core Data - the view doesn't care.

In short, using the delegate design pattern (in Cocoa or in WPF, for that matter) gives me a level of flexibility and agility that I don't normally see with desktop applications. I'm finding that there are a lot of things that I can do elegantly, simply, and quickly using this pattern that I found tedious or cumbersome using traditional data binding.

tags:          
links: digg this  del.icio.us  technorati  reddit

More Stories By Kevin Hoffman

Kevin Hoffman, editor-in-chief of SYS-CON's iPhone Developer's Journal, has been programming since he was 10 and has written everything from DOS shareware to n-tier, enterprise web applications in VB, C++, Delphi, and C. Hoffman is coauthor of Professional .NET Framework (Wrox Press) and co-author with Robert Foster of Microsoft SharePoint 2007 Development Unleashed. He authors The .NET Addict's Blog at .NET Developer's Journal.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
news desk 05/15/07 08:28:43 AM EDT

Cocoa - Exploring the Delegate Design Pattern

@ThingsExpo Stories
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. ANSeeN are the measurement electronics maker for X-ray and Gamma-ray and Neutron measurement equipment such as spectrometers, pulse shape analyzer, and CdTe-FPD. For more information, visit http://anseen.com/.
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
SYS-CON Events announced today that CAST Software will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
Organizations do not need a Big Data strategy; they need a business strategy that incorporates Big Data. Most organizations lack a road map for using Big Data to optimize key business processes, deliver a differentiated customer experience, or uncover new business opportunities. They do not understand what’s possible with respect to integrating Big Data into the business model.
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
Amazon is pursuing new markets and disrupting industries at an incredible pace. Almost every industry seems to be in its crosshairs. Companies and industries that once thought they were safe are now worried about being “Amazoned.”. The new watch word should be “Be afraid. Be very afraid.” In his session 21st Cloud Expo, Chris Kocher, a co-founder of Grey Heron, will address questions such as: What new areas is Amazon disrupting? How are they doing this? Where are they likely to go? What are th...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.