Standard single-instance notation
Create a song with the manager as an example.
+ (instancetype) sharedqysongmanager{ static
static dispatch_once_t Oncetoken; //executes a block object once and only once for the lifetime of a application. Dispatch_once (&oncetoken,^{ songmanager =[[self alloc] init]; }); return Songmanager;}
Once created, Songmanager is the singleton object, that is, in memory regardless of how many objects are alloc the same object.
There are a few points to note:
What is 1.instancetype?
Apple's official explanation is: Use the instancetype keyword as the return type of methods that return an instance of the class they a Re called on (or a subclass of the that class). These methods include alloc, init, and class factory methods.
//ios Development:CLang added a new keyword:instancetype; This is a context-sensitive keyword and can only be used as the return type of the objective-c method. Using instancetype allows the compiler to accurately infer the exact type of return, exposing some runtime errors at compile time
Let's take a look at an Apple official example
@interfaceMyobject:nsobject+(instancetype) Factorymethoda;+ (ID) Factorymethodb;@end @implementationMyObject+ (Instancetype) Factorymethoda {return[[Selfclass] [alloc] init]; }+ (ID) Factorymethodb {return[[Selfclass] [alloc] init]; }@end voiddosomething () {Nsuinteger x, y; X= [[MyObject Factorymethoda] count];//Return type of +factorymethoda is taken to being "MyObject *"y = [[MyObject Factorymethodb] count];//Return type of +FACTORYMETHODB is "id"}
Because of the instancetype return type of + Factorymethoda, the type of the message expression is myobject*. Since MyObject does not have a counting method, the compiler gives a warning about X-lines:
MAIN.M: ' MyObject ' may isn't respond to ' count '
2. To be continued to be completed tomorrow