such as ticket class ticket, guarantee ticket only created once.
1. Define static global variable Ticket *sharedinstance;
A variable that defines the number of votes @property (assign,atomic) Nsinteger tickets;
The Atomic atomic attribute, which is accessed by one thread in multiple threads, is inaccessible to other threads.
Plus sync lock @synchronized
2. Create a new ticket class, overriding the Allocwithzone method
+ (ID) Allocwithzone: (Nszone *) zone
{
Multithreading
Static dispath_once_t Oncetoken;
Dispath_once (&oncetoken,^{
Sharedinstance = [Super Allocwithzone:zone];
});
Single Thread
if (sharedinstance = = nil)
//{
Sharedinstance = [Super Allocwithzone:zone];
//}
return sharedinstance;
}
3. Easy to call
+ (ticket*) sharedticket
{
Static dispatch_once_t Oncetoken;
Dispatch_one (&oncetoken,^{
Sharedinstance = [[Ticket alloc]init];
});
return ticket;
}
IOS-Singleton mode + multithreading