) Objective-C Singleton)

Source: Internet
Author: User

(From: http://blog.csdn.net/arthurchenjs/article/details/6699598)

If you want to write a class to ensure that only one instance exists and you can get the entry for providing services for this specific instance, you can use the single-State design mode.

The single-State mode is commonly used in Java and C ++. It can also be implemented in cocoa.

However,

The objective-C Singleton mode is definitely different from what you think. Its writing method is different from the writing method in all languages you have ever seen.

 

Official recommendations

 

Because it is risky to design the single-State mode, it is mainly because of problems that may occur in the case of multithreading. Therefore, Apple officially recommends using the following methods to implement the single-State mode:

Static mygizmoclass * sharedgizmomanager = nil;
+ (Mygizmoclass *) sharedmanager
{
@ Synchronized (Self ){
If (sharedgizmomanager = nil ){
[[Self alloc] init]; // assignment not done here
}
}
Return sharedgizmomanager;
}
+ (ID) allocwithzone :( nszone *) Zone
{
@ Synchronized (Self ){
If (sharedgizmomanager = nil ){
Sharedgizmomanager = [Super allocwithzone: Zone];
Return sharedgizmomanager; // assignment and return on first allocation
}
}
Return nil; // on subsequent allocation attempts return Nil
}
-(ID) copywithzone :( nszone *) Zone
{
Return self;
}
-(ID) Retain
{
Return self;
}
-(Unsigned) retaincount
{
Return uint_max; // denotes an object that cannot be released
}
-(Void) Release
{
// Do nothing
}
-(ID) autorelease
{
Return self;
}

 

Open-source template (Attachment)

ProgramThe employees are all lazy. Nowadays, we are using a macro definition to deal with these many things, and we have considered them more comprehensively.

The Singleton includes the following APIs:

+ (Myclass *) sharedinstance;
+ (Void) purgesharedinstance;

 

When sharedinstance is called, a single instance is created and returned.

Calling purgesharedinstance will destroy the singleton

Manually calling alloc can also be a singleton. You can call

[[Myclass alloc] initwithparam: firstparam secondparam: secondparam];

You only need to ensure that it is called before sharedinstance, because there is only one creation opportunity.

The following is a macro statement:

Myclass. h:
==========================================================
# Import "synthesizesingleton. H"

@ Interface myclass: somesuperclass
{
...
}
Synthesize_singleton_for_class_header (myclass );

@ End
==========================================================

Myclass. M:
==========================================================
# Import "myclass. H"

@ Implementation myclass

Synthesize_singleton_for_class (myclass );

...

@ End
==========================================================

Http://arthurchen.blog.51cto.com/attachment/201108/2483760_1313658868.rar

 

The above is reproduced.

---------------------------------- Split line ------------------------------------

The following is a supplement provided by xiaou:

The downloadedOpen source TemplateThe content is as follows: (I have modified one or two compiled errors in xcode4 environment)

File Name: synthesizesingleton. h

---------------------------------- Split line ------------------------------------

# Ifndef synthesize_singleton_for_class

# Import <Objc/runtime. h>


# Pragma Mark-
# Pragma Mark Singleton

/* Synthesize Singleton for class
*
* Creates a singleton interface for the specified class with the following methods:
*
* + (Myclass *) sharedinstance;
* + (Void) purgesharedinstance;
*
* Calling sharedinstance will instantiate the class and swizzle some methods to ensure
* That only a single instance ever exists.
* Calling purgesharedinstance will destroy the shared instance and return the swizzled
* Methods to their former selves.
*
*
* Usage:
*
* Myclass. h:
* ===================================================== =
* # Import "synthesizesingleton. H"
*
* @ Interface myclass: somesuperclass
*{
*...
*}
* Synthesize_singleton_for_class_header (myclass );
*
* @ End
* ===================================================== =
*
*
* Myclass. M:
* ===================================================== =
* # Import "myclass. H"
*
* @ Implementation myclass
*
* Synthesize_singleton_for_class (myclass );
*
*...
*
* @ End
* ===================================================== =
*
*
* Note: Calling alloc manually will also initialize the Singleton, So you
* Can call a more complex init routine to initialize the singleton like so:
*
* [[Myclass alloc] initwithparam: firstparam secondparam: secondparam];
*
* Just be sure to make such a call before you call "sharedinstance" in
* Your program.
*/

# Define Synthesize_singleton_for_class_header (_ classname __)\
\
+ (_ Classname _ *) sharedinstance ;\
+ ( Void ) Purgesharedinstance;


# Define Synthesize_singleton_for_class (_ classname __)\
\
Static _ Classname __* Volatile _ ##__ Classname __##_ sharedinstance = nil ;\
\
+ (_ Classname _ *) sharedinstancenosynch \
{\
Return (_ Classname _ *) _ ##__ classname __##_ sharedinstance ;\
}\
\
+ (_ Classname _ *) sharedinstancesynch \
{\
@ Synchronized (Self )\
{\
If (Nil ==##__ classname __##_ sharedinstance )\
{\
_ ##__ Classname __##_ sharedinstance = [[self alloc] init]; \
}\
Else \
{\
Nsassert2 ( 1 = 0 , @" Synthesizesingleton: % @ error: + (% @ *) sharedinstance method did not get swizzled. " , Self, self );\
}\
}\
Return (_ Classname _ *) _ ##__ classname __##_ sharedinstance ;\
}\
\
+ (_ Classname _ *) sharedinstance \
{\
Return [Self sharedinstancesynch]; \
}\
\
+ ( ID ) Allocwithzone :( nszone *) Zone \
{\
@ Synchronized (Self )\
{\
If (Nil ==##__ classname __##_ sharedinstance )\
{\
_ ##__ Classname __##_ sharedinstance = [Super allocwithzone: Zone]; \
If (Nil! ==##__ Classname __###_ sharedinstance )\
{\
Method newsharedinstancemethod = class_getclassmethod (self, @ selector (sharedinstancenosynch ));\
Method_setimplementation (class_getclassmethod (self, @ selector (sharedinstance), method_getimplementation (newsharedinstancemethod ));\
Method_setimplementation (class_getinstancemethod (self, @ selector (retaincount), class_getmethodimplementation (self, @ selector (retaincountdonothing )));\
Method_setimplementation (class_getinstancemethod (self, @ selector (release), class_getmethodimplementation (self, @ selector (releasedonothing )));\
Method_setimplementation (class_getinstancemethod (self, @ selector (autorelment)), class_getmethodimplementation (self, @ selector (autoreleasedonothing )));\
}\
}\
}\
Return _ ##__ Classname __##_ sharedinstance ;\
}\
\
+ ( Void ) Purgesharedinstance \
{\
@ Synchronized (Self )\
{\
If (Nil! ==##__ Classname __###_ sharedinstance )\
{\
Method newsharedinstancemethod = class_getclassmethod (self, @ selector (sharedinstancesynch ));\
Method_setimplementation (class_getclassmethod (self, @ selector (sharedinstance), method_getimplementation (newsharedinstancemethod ));\
Method_setimplementation (class_getinstancemethod (self, @ selector (retaincount), class_getmethodimplementation (self, @ selector (retaincountdosomething )));\
Method_setimplementation (class_getinstancemethod (self, @ selector (release), class_getmethodimplementation (self, @ selector (releasedosomething )));\
Method_setimplementation (class_getinstancemethod (self, @ selector (autorelment)), class_getmethodimplementation (self, @ selector (autoreleasedosomething )));\
[_ ##__ Classname __###_ sharedinstance release]; \
_ ##__ Classname __##_ sharedinstance = nil ;\
}\
}\
}\
\
-( ID ) Copywithzone :( nszone *) Zone \
{\
Return Self ;\
}\
\
-( ID ) Retain \
{\
Return Self ;\
}\
\
-(Nsuinteger) retaincount \
{\
Nsassert1 ( 1 = 0 , @" Synthesizesingleton: % @ error:-(nsuinteger) retaincount method did not get swizzled. " , Self );\
Return Nsuintegermax ;\
}\
\
-(Nsuinteger) retaincountdonothing \
{\
Return Nsuintegermax ;\
}\
-(Nsuinteger) retaincountdosomething \
{\
Return [Super retaincount]; \
}\
\
-(Oneway Void ) Release \
{\
Nsassert1 ( 1 = 0 , @" Synthesizesingleton: % @ error:-(void) release method did not get swizzled. " , Self );\
}\
\
-( Void ) Releasedonothing {}\
\
-( Void ) Releasedosomething \
{\
@ Synchronized (Self )\
{\
[Super release]; \
}\
}\
\
-( ID ) Autorelease \
{\
Nsassert1 ( 1 = 0 , @" Synthesizesingleton: % @ error:-(ID) autorelease method did not get swizzled. " , Self );\
Return Self ;\
}\
\
-( ID ) Autoreleasedonothing \
{\
Return Self ;\
}\
\
-( ID ) Autoreleasedosomething \
{\
Return [Super autorelease]; \
}

# Endif
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.