Академический Документы
Профессиональный Документы
Культура Документы
Problem
Many examples found online utilize the AppDelegate instance for global storage/variables. While
this is a quick way of sharing data and methods between views and classes it can (and usually
does) lead to several problems:
No control over global variables/storage
Each referencing class assumes direct control over this variable and wont necessarily respect how
another class is expecting to use it. With a singleton, the data has been fully encapsulated and
controlled in one place.
Repeated business logc
If there is any business logic on how this global storage is to be used it has to be repeated
throughout the application. While some may encapsulate this by using accessor methods the
logic is in the wrong place.
Big Ball Of Mud
Very quickly, the AppDelegate class will become a big ball of mud and VERY difficult to maintain.
This is compounded over time as the app is revisioned and different developers add more and
more code to the ball of mud.
together with the confidence that the same data will be retained throughout the application. In
fact, the AppDelegate is held in a singleton of your application ([UIApplication
sharedApplication]).
The developer must also ensure to not repeat the same big ball of mud anti-pattern by simply
moving all the code from the AppDelegate into one Singleton class. The concept of single-purpose
classes will be covered in a future post.
Implementation
2. Leverage public shared methods as a convenience factor to encourage use of the singleton.
1
2
3
4
5
+(NSString
*)
getSomeData
{
//
Ensure
we
are
using
the
shared
instance
SingletonSample
*shared
=
[SingletonSample
sharedInstance];
return
shared.someData;
}
3. Create and use instance variables and methods as you normally would
1
2
3
4
5
6
7
8
-
(IBAction)singletonTouched:(id)sender
{
//
Using
the
convenience
method
simplifies
the
code
even
more
self.singletonLabel.text
=
[SingletonSample
getSomeData];
Reply
3. Jeremias Nuez says:
April 4, 2013 at 11:43 pm
note that @synchronized will only make the creation thread safe. further access to the singleton
will NOT be thread safe.
you can also use dispatch_once for this:
+ (SingletonSample*)sharedInstance {
static ILTestSingleton* instance;
static dispatch_once_t onceToken = 0;
dispatch_once(&onceToken, ^{
instance = [[SingletonSample alloc] init];
});
return instance;
}
Reply
4. Pingback: Class Cluster as a Singleton? | BlogoSfera