IOS development basics-singleton Mode

Source: Internet
Author: User

Singleton design mode. This mode is often controversial, so I want to explain the singleton here.

In principle, Singleton is a class that is instantiated only once in the life cycle of a program. To ensure this, we use a static method of the class to generate and access objects.

Therefore, you access the singleton object of a class by using the method of benefit, rather than using alloc/init or static autorelease initialization method.

In many cases, we use a unique instance of a class. The most common is the main class of a program.

The following is a singleton function created with the name rootviewcontroller:

Static rootviewcontroller * sharedrootcontroller = nil;
 
+ (Rootviewcontroller *) sharedcontroller {
@ Synchronized (Self ){
If (sharedrootcontroller = nil ){
Sharedrootcontroller = [[self alloc] init] autorelease];
}
}
Return singlecontroller;
}
+ (ID) allocwithzone :( nszone *) Zone {
@ Synchronized (Self ){
If (sharedrootcontroller = nil ){
Sharedrootcontroller = [Super allocwithzone: Zone];
Return sharedrootcontroller;
}
}
Return nil;
}


Code Description:

1. synchronized is mainly a multi-threaded program. This command can limit the code in {} to one thread for execution. If a thread is not finished, other threads have to wait if they need to be executed.
2. The online search code seems to have been not added to autorelease. I think it should be added. This is because it is troublesome to call a function without release. (I personally think that for programs on iOS, autorelease should be taken into account for the creation of function return values)
3. allocwithzone is overloaded because it reads information from the specified memory area to create an instance. Therefore, if you need a Singleton, you must disable the modification of the current Singleton. Therefore, Nil is returned.

Related Article

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.