How do I convert (or create) a singleton class that compiles and behaves correctly when using automatic reference counting (ARC) in Xcode 4.2?
相关问题
- suppress a singleton constructor in java with powe
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
相关文章
- 现在使用swift开发ios应用好还是swift?
- UITableView dragging distance with UIRefreshContro
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- Swift - hide pickerView after value selected
- How can I add media attachments to my push notific
Hope above code will help it out.
This is a version for ARC and non-ARC
How To use:
MySingletonClass.h
MySingletonClass.m
In exactly the same way that you (should) have been doing it already:
Read this answer and then go and read the other answer.
You must first know what does a Singleton mean and what are its requirements, if you don't understand it, than you won't understand the solution--at all!
To create a Singleton successfully you must be able to do the following 3:
dispatch_once_t
helps you to solve a race condition by only allowing its block to be dispatched once.Static
helps you to “remember” its value across any number of invocations. How does it remember? It doesn't allow any new instance with that exact name of your sharedInstance to be created again it just works with the one that was created originally.Not using calling
alloc
init
(i.e. we still havealloc
init
methods since we are an NSObject subclass, though we should NOT use them) on our sharedInstance class, we achieve this by using+(instancetype)sharedInstance
, which is bounded to only be initiated once, regardless of multiple attempts from different threads at the same time and remember its value.Some of the most common system Singletons that come with Cocoa itself are:
[UIApplication sharedApplication]
[NSUserDefaults standardUserDefaults]
[NSFileManager defaultManager]
[NSBundle mainBundle]
[NSOperations mainQueue]
[NSNotificationCenter defaultCenter]
Basically anything that would need to have centralized effect would need to follow some sort of a Singleton design pattern.
There are two issues with the accepted answer, which may or may not be relevant for your purpose.
The following code takes care of both of these problems:
if you need to create singleton in swift,
or
you can use this way