First, use @ synchronized (self)
Static LocationController * sharedInstance;
+ (LocationController *) sharedInstance {
@ Synchronized (self ){
If (! SharedInstance)
SharedInstance = [[LocationController alloc] init];
}
Return sharedInstance;
}
@ Synchronized
Role: Creates a mutex lock. It works the same way as mutex in other languages.
Explanation: This is a lock token in Objective-C, which facilitates an object to be accessed by other threads at the same time and plays the role of thread protection.
Usage scope: generally used when the single-instance mode or static variable of the operation class is used, that is, when the shared variable is used.
Extension: This token implicitly contains Exception Handling. If you do not want to use it, use the lock.
Second, use GCD
Static LocationController * sharedInstance;
+ (LocationController *) sharedInstance {
Static dispatch_once_t onceToken;
Dispatch_once (& onceToken, ^ {
If (! SharedInstance)
SharedInstance = [[self alloc] init];
});
Return sharedInstance;
}
There is a simpler and more effective way to implement ios3.2. It is through the Grand Central Dispatch System. Whenever you need to run a transaction in the background, you just need to call dispatch_async and pass the transaction code to be executed.
In fact, Grand Central Dispatch hides many background processing details, such as the lock and synchronization mechanism, and creates a new thread or uses an existing thread as needed.
When you call dispatch_async, there are a lot of blocks in this queue through a dispatch queue, which are first-in-first-out and executed in sequence.
This queue can be created by using dispatch_create, or the main thread queue dispatch_get_main_queue can be called. The name of the created queue is onceToken.
Third, use NSOperationQueue
However, ios encapsulates Grand Central Dispatch and generates a new class NSOperationQueue.
Therefore, using NSOperationQueue is to use Grand Central Dispatch, and NSOperationQueue is just a simple API built on Grand Central Dispatch.
Static LocationController * sharedInstance;
+ (LocationController *) sharedInstance {
NSOperationQueue * onceToken = [[NSOperationQueue alloc] init];
[OnceToken addOperationWithBlock: ^ (){
If (! SharedInstance)
SharedInstance = [[self alloc] init];
});
Return sharedInstance;
}];
}
Share: