Welcome!

Microsoft Cloud Authors: David H Deans, Yeshim Deniz, Janakiram MSV, 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
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
Recently, IoT seems emerging as a solution vehicle for data analytics on real-world scenarios from setting a room temperature setting to predicting a component failure of an aircraft. Compared with developing an application or deploying a cloud service, is an IoT solution unique? If so, how? How does a typical IoT solution architecture consist? And what are the essential components and how are they relevant to each other? How does the security play out? What are the best practices in formulating...
In his session at @ThingsExpo, Arvind Radhakrishnen discussed how IoT offers new business models in banking and financial services organizations with the capability to revolutionize products, payments, channels, business processes and asset management built on strong architectural foundation. The following topics were covered: How IoT stands to impact various business parameters including customer experience, cost and risk management within BFS organizations.
SYS-CON Events announced today that Elastifile 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. Elastifile Cloud File System (ECFS) is software-defined data infrastructure designed for seamless and efficient management of dynamic workloads across heterogeneous environments. Elastifile provides the architecture needed to optimize your hybrid cloud environment, by facilitating efficient...
SYS-CON Events announced today that Golden Gate University 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. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
SYS-CON Events announced today that DXWorldExpo has been named “Global 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics ...
21st International Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Me...
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
There is only one world-class Cloud event on earth, and that is Cloud Expo – which returns to Silicon Valley for the 21st Cloud Expo at the Santa Clara Convention Center, October 31 - November 2, 2017. Every Global 2000 enterprise in the world is now integrating cloud computing in some form into its IT development and operations. Midsize and small businesses are also migrating to the cloud in increasing numbers. Companies are each developing their unique mix of cloud technologies and service...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, will introduce two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a...
SYS-CON Events announced today that Secure Channels, a cybersecurity firm, 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. Secure Channels, Inc. offers several products and solutions to its many clients, helping them protect critical data from being compromised and access to computer networks from the unauthorized. The company develops comprehensive data encryption security strategie...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
SYS-CON Events announced today that App2Cloud 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. App2Cloud is an online Platform, specializing in migrating legacy applications to any Cloud Providers (AWS, Azure, Google Cloud).
IoT is at the core or many Digital Transformation initiatives with the goal of re-inventing a company's business model. We all agree that collecting relevant IoT data will result in massive amounts of data needing to be stored. However, with the rapid development of IoT devices and ongoing business model transformation, we are not able to predict the volume and growth of IoT data. And with the lack of IoT history, traditional methods of IT and infrastructure planning based on the past do not app...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. Jack Norris reviews best practices to show how companies develop, deploy, and dynamically update these applications and how this data-first...
Internet-of-Things discussions can end up either going down the consumer gadget rabbit hole or focused on the sort of data logging that industrial manufacturers have been doing forever. However, in fact, companies today are already using IoT data both to optimize their operational technology and to improve the experience of customer interactions in novel ways. In his session at @ThingsExpo, Gordon Haff, Red Hat Technology Evangelist, shared examples from a wide range of industries – including en...
Intelligent Automation is now one of the key business imperatives for CIOs and CISOs impacting all areas of business today. In his session at 21st Cloud Expo, Brian Boeggeman, VP Alliances & Partnerships at Ayehu, will talk about how business value is created and delivered through intelligent automation to today’s enterprises. The open ecosystem platform approach toward Intelligent Automation that Ayehu delivers to the market is core to enabling the creation of the self-driving enterprise.