Standard creation method for singleton objects in iOS development

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.