{"id":568763,"date":"2010-05-18T11:25:08","date_gmt":"2010-05-18T15:25:08","guid":{"rendered":"https:\/\/gigapple.wordpress.com\/?p=44800"},"modified":"2010-05-18T11:25:08","modified_gmt":"2010-05-18T15:25:08","slug":"iphone-dev-sessions-using-singletons","status":"publish","type":"post","link":"https:\/\/mereja.media\/index\/568763","title":{"rendered":"iPhone Dev Sessions: Using Singletons"},"content":{"rendered":"<p>Managing an application\u2019s state can sometimes require complex interaction with persistence and messaging with various resources, or it can be as simple as keeping track of a counter from one view to the next.<\/p>\n<p>Two popular techniques to pass references to objects from one view to the next are to create properties in the Application Delegate, or to continue to pass references from one view to the next like a relay race passes a baton from one runner to the next using a series of carefully placed update methods making for an allocation nightmare and increase the opportunities for memory leaks or the hard to track down crashes. Sometimes this need in programming is referred to as implementing Global Variables. There is also a well established design pattern that can assist with this need as well, it is called the Singleton Pattern.<\/p>\n<h2><strong>Singleton Pattern<br \/>\n<\/strong><\/h2>\n<p>The Singleton Pattern is a derivative of the Factory Pattern that ensures that one and only one instance of an Object can ever exist. By creating one or more implementations of the Singleton Pattern within a given application, the concept of \u2018global variables\u2019 can better be managed through tighter control. This allows for what is called lazy instantiation. If you do not need the variable based on what is going on in the application, then do not ask for or create an instance of one.\u00a0 In Objective-C, Apple has outlined the recommended technique for implementing the singleton pattern.<\/p>\n<div id=\"attachment_45007\" class=\"wp-caption aligncenter\" style=\"width: 310px\"><img loading=\"lazy\" decoding=\"async\"  title=\"Objective-C Singleton Pattern\" src=\"http:\/\/gigapple.files.wordpress.com\/2010\/04\/objectivec-singletonpattern.png?w=300&#038;h=296\" alt=\"Objective-C Singleton Pattern\" width=\"300\" height=\"296\" class=\"size-medium wp-image-45007\" \/><\/p>\n<p class=\"wp-caption-text\">Objective-C Singleton Pattern<\/p>\n<\/div>\n<pre class=\"brush: objc;\">\nstatic MySingletonClass *sharedGizmoManager = nil;\n(MySingletonClass*)sharedManager{\n  if (sharedSingletonManager == nil) {\n    sharedSingletonManager = [[super allocWithZone:NULL] init];\n  }\n  return sharedGizmoManager;\n}\n(id)allocWithZone:(NSZone *)zone{\n  return [[self sharedManager] retain];\n}\n(id)copyWithZone:(NSZone *)zone{\n  return self;\n}\n(id)retain{\n  return self;\n}\n(NSUInteger)retainCount{\n  return NSUIntegerMax;\n}\n(void)release{\n  \/\/do nothing\n}\n(id)autorelease{\n  return self;\n}\n<\/pre>\n<p>But you may find that the following is all that is necessary:<\/p>\n<p><em><strong>Singleton.h<\/strong><\/em><\/p>\n<pre class=\"brush: objc;\">\n#import &lt;Foundation\/Foundation.h&gt;\n@interface Singleton : NSObject {\n}\n+ (Singleton*) retrieveSingleton;\n@end\n<\/pre>\n<p><em><strong>Singleton.m<\/strong><\/em><\/p>\n<pre class=\"brush: objc;\">\n#import &quot;Singleton.h&quot;\n@implementation Singleton\nstatic Singleton *sharedSingleton = nil;\n+ (Singleton*) retrieveSingleton {\n  @synchronized(self) {\n    if (sharedSingleton == nil) {\n      sharedSingleton = [[Singleton alloc] init];\n    }\n  }\n  return sharedSingleton;\n}\n+ (id) allocWithZone:(NSZone *) zone {\n  @synchronized(self) {\n    if (sharedSingleton == nil) {\n      sharedSingleton = [super allocWithZone:zone];\n      return sharedSingleton;\n    }\n  }\n  return nil;\n}\n@end\n<\/pre>\n<p>Try and keep each singleton\u2019s scope limited to manage only the information that is related to a particular use case and not as a catch-all for all global information across the application. It is probably best to utilize each singleton as a delegate to the information it is responsible for managing, and not use it as a means to gain access to any objects it has associations with. Although on the iPhone, and when being used in primarily a read only or a write seldom implementation, the risk of writing code that is not thread safe increases when utilizing shared objects. Keeping concurrency in mind, and utilizing the singleton as a delegate to the information at hand, one can watch out for multi thread related issues and deal with them in kind. One thing to watch out for would be include updating or setting properties of the singleton from within an implemented perform selector or a notification. If concurrency issues do arise, it may become necessary to synchronize access to certain properties or methods.<\/p>\n<h2><strong>No, not the AppDelegate!<\/strong><\/h2>\n<p>So why not just keep adding properties to the AppDelegate? After all, the AppDelegate is a singleton as well and is therefore accessible by invoking the sharedApplication class method. The problem with this techniques is that you end up loading up the application with too much information that may or may not be necessary depending on what functions the user chooses to evoke. It could also lead to longer and longer startup times. Get the application started as quickly as possible, and don\u2019t leave the user hanging for too long.<\/p>\n<h2><strong>What about Global Constants?<\/strong><\/h2>\n<p>Keep in mind that this is not the best technique to employ if all you need is a means to define and gain access to Global Constants. The quickest way to do that is to create a Precompiled Prefix Header file and include that in your project. By default, most of the projects generated in XCode that create iPhone Applications will include a file with an extension of .pch. This file will initially look like the following:<\/p>\n<pre class=\"brush: objc;\">\n#ifdef __OBJC__\n#import &lt;Foundation\/Foundation.h&gt;\n#import &lt;UIKit\/UIKit.h&gt;\n#endif\n<\/pre>\n<p>One can then add any number of #define statements that will be included in all header files across the entire project.<\/p>\n<pre class=\"brush: objc;\">\n#define SOME_STRING_CONSTANT @&quot;My Important String&quot;\n<\/pre>\n<h2><strong>Conclusion<\/strong><\/h2>\n<p>The Singleton Pattern can be used to make the complex and ugly means of sharing a simple variable between two different views or view controls an easy task. If used sparingly and some basic guidelines are followed as not to bloat the application and create a multi thread nightmare to debug, this technique can be quite useful. Much more so than passing Objects back and forth among views or by breaking the encapsulation of the AppDelegate by assigning it more responsibility than it should have.<\/p>\n<p><em>References<\/em><\/p>\n<ul>\n<li><a href=\"http:\/\/developer.apple.com\/mac\/library\/documentation\/Cocoa\/Conceptual\/CocoaFundamentals\/CocoaObjects\/CocoaObjects.html#\/\/apple_ref\/doc\/uid\/TP40002974-CH4-SW32\">Mac OS X Reference Library &#8211; Cocoa Fundamentals Guide &#8211; Creating a Singleton Instance<\/a><\/li>\n<li><a href=\"https:\/\/developer.apple.com\/iphone\/library\/documentation\/UIKit\/Reference\/UIApplication_Class\/Reference\/Reference.html\">iPhone OS Reference Library &#8211; UIApplication Class Reference<\/a><\/li>\n<li><a href=\"http:\/\/developer.apple.com\/mac\/library\/DOCUMENTATION\/DeveloperTools\/Conceptual\/XcodeBuildSystem\/800-Reducing_Build_Times\/bs_speed_up_build.html#\/\/apple_ref\/doc\/uid\/TP40002695-SW1\">Mac OS X Reference Library &#8211; Xcode Build system Guide &#8211; Using a Precompiled Prefix Header<\/a><\/li>\n<\/ul>\n<p><img decoding=\"async\" alt=\"\" border=\"0\" src=\"http:\/\/stats.wordpress.com\/b.gif?host=theappleblog.com&#038;blog=5550580&#038;post=44800&#038;subd=gigapple&#038;ref=&#038;feed=1\" \/><\/p>\n<hr \/>\n<p>\n\t<a href='http:\/\/gigaom.com\/sponsor\/alcatel-lucent\/?utm_source=RSS&amp;utm_medium=Banner&amp;utm_campaign=RSS%2BLucent'><br \/>\n\t\t<img src='http:\/\/a.gigaom.com\/feed-injector\/img\/lucent-2010-05-17.gif' alt='Alcatel-Lucent NextGen Communications Spotlight &mdash; Learn More &raquo;' border='0' \/><br \/>\n\t<\/a>\n<\/p>\n<div class=\"feedflare\">\n<a href=\"http:\/\/feeds.feedburner.com\/~ff\/TheAppleBlog?a=q-XEdpmrqRM:HMnk5E7NXu0:yIl2AUoC8zA\"><img decoding=\"async\" src=\"http:\/\/feeds.feedburner.com\/~ff\/TheAppleBlog?d=yIl2AUoC8zA\" border=\"0\"><\/img><\/a> <a href=\"http:\/\/feeds.feedburner.com\/~ff\/TheAppleBlog?a=q-XEdpmrqRM:HMnk5E7NXu0:D7DqB2pKExk\"><img decoding=\"async\" src=\"http:\/\/feeds.feedburner.com\/~ff\/TheAppleBlog?i=q-XEdpmrqRM:HMnk5E7NXu0:D7DqB2pKExk\" border=\"0\"><\/img><\/a> <a href=\"http:\/\/feeds.feedburner.com\/~ff\/TheAppleBlog?a=q-XEdpmrqRM:HMnk5E7NXu0:V_sGLiPBpWU\"><img decoding=\"async\" src=\"http:\/\/feeds.feedburner.com\/~ff\/TheAppleBlog?i=q-XEdpmrqRM:HMnk5E7NXu0:V_sGLiPBpWU\" border=\"0\"><\/img><\/a> <a href=\"http:\/\/feeds.feedburner.com\/~ff\/TheAppleBlog?a=q-XEdpmrqRM:HMnk5E7NXu0:F7zBnMyn0Lo\"><img decoding=\"async\" src=\"http:\/\/feeds.feedburner.com\/~ff\/TheAppleBlog?i=q-XEdpmrqRM:HMnk5E7NXu0:F7zBnMyn0Lo\" border=\"0\"><\/img><\/a> <a href=\"http:\/\/feeds.feedburner.com\/~ff\/TheAppleBlog?a=q-XEdpmrqRM:HMnk5E7NXu0:guobEISWfyQ\"><img decoding=\"async\" src=\"http:\/\/feeds.feedburner.com\/~ff\/TheAppleBlog?i=q-XEdpmrqRM:HMnk5E7NXu0:guobEISWfyQ\" border=\"0\"><\/img><\/a>\n<\/div>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/feeds.feedburner.com\/~r\/TheAppleBlog\/~4\/q-XEdpmrqRM\" height=\"1\" width=\"1\"\/><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Managing an application\u2019s state can sometimes require complex interaction with persistence and messaging with various resources, or it can be as simple as keeping track of a counter from one view to the next. Two popular techniques to pass references to objects from one view to the next are to create properties in the Application [&hellip;]<\/p>\n","protected":false},"author":6816,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[],"class_list":["post-568763","post","type-post","status-publish","format-standard","hentry","category-news"],"_links":{"self":[{"href":"https:\/\/mereja.media\/index\/wp-json\/wp\/v2\/posts\/568763","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mereja.media\/index\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mereja.media\/index\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mereja.media\/index\/wp-json\/wp\/v2\/users\/6816"}],"replies":[{"embeddable":true,"href":"https:\/\/mereja.media\/index\/wp-json\/wp\/v2\/comments?post=568763"}],"version-history":[{"count":0,"href":"https:\/\/mereja.media\/index\/wp-json\/wp\/v2\/posts\/568763\/revisions"}],"wp:attachment":[{"href":"https:\/\/mereja.media\/index\/wp-json\/wp\/v2\/media?parent=568763"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mereja.media\/index\/wp-json\/wp\/v2\/categories?post=568763"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mereja.media\/index\/wp-json\/wp\/v2\/tags?post=568763"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}