[IOS] single case of ARC-MRC and its application, iosmrcarc

Source: Internet
Author: User

[IOS] single case of ARC-MRC and its application, iosmrcarc

Singleton is widely used,In Singleton mode, a class has only one instance..

* It is easy for external access. * It is convenient to control the number of instances and save system resources.
* Common examples in OC: UIApplication, nsnotifcenter center, NSUserDefaults, and NSFIleManager.
* Single example used in the application, such as background music and sound effect management.

1. single example in ARC

Create a singleton: * 1. defines a Global static variable _ instance to record the objects instantiated for the first time. * 2. override the allocWithZone method. This method is a method that must be called to allocate memory space for the object! Therefore, using "dispatch_once" in this method can ensure that _ instance can be allocated only once in multiple threads. * 3. defines a sharedXXX "class" method to facilitate other Singleton objects to call this Singleton. in this method, "dispatch_once" is also used to ensure that the object called using the class method will only be initialized once! Note: If you do not consider copy & MRC, you can do the above three steps! * 4. To support copy, you need to: (1) comply with the NSCopying protocol (2) directly return _ instance in the copyWithZone Method


Tips:

* General statement (lazy, hungry, locking): if (! _ Instance) _ instance = [[xnsharsponlalloc] init]; return_instance; * lazy is Thread SecuritySo it is not written in reality. There are hunger, locking, and so on.
* However, OC has its own writing method. You need to use some methods of its object lifecycle to write a singleton.
* Why use dispatch_one? : To prevent multiple threads from coming in at the same time, it is equivalent to the locking mechanism in the Java Singleton to ensure that it is instantiated only once. however, synchronized is not used here. It is similar to mutex lock, but it has higher performance than synchronized.
The code for implementing Singleton in ARC is as follows:
@ Implementation XNShareTool/** step: 1. A static variable _ inastance 2. override allocWithZone, use dispatch_once in it, and call super allocWithZone 3. customizes A sharedXX instance to obtain a singleton. call dispatch_once, and instantiate _ instance ----------- optional ------------ 4. if you want to support copy. then (first comply with the NSCopying protocol) rewrite copyWithZone and directly return _ instance. * // ** Step 2: store the unique instance */static XNShareTool * _ instance;/** Step 2: Call this method when allocating memory holes. ensure that the allocated memory alloc is the same */+ (id) allocWithZone :( struct _ NSZone *) zone {// call dispatch_once to ensure that only one static dispatch_once_t onceToken is instantiated in multiple threads; dispatch_once (& onceToken, ^ {_ instance = [super allocWithZone: zone] ;}); return _ instance ;}/ ** Step 2: ensure that the init Initialization is the same */+ (instancetype) sharedTool {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {_ instance = [[XNShareTool alloc] init];}); return _ instance;}/** Step 2: Ensure that all copies are the same */-(id) copyWithZone :( NSZone *) zone {return _ instance;} @ end

The test code is as follows (print The addresses are the same.):

-(Void) viewDidLoad {// Several Methods for instantiating a class. singleton is to ensure that the instantiated class is the same class // 1. alloc init method. this is generally not the case for calling a singleton. XNShareTool * t1 = [[XNShareTool alloc] init]; XNShareTool * t2 = [[XNShareTool alloc] init]; // 2. class Method XNShareTool * t3 = [XNShareTool sharedTool]; // 3. copy XNShareTool * t4 = [t3 copy]; NSLog (@ "% @", t1, t2, t3, t4 );}


Ii. Use a ticket in MRC


Because the singleton object is marked with static, it is stored in the static zone. Therefore, it does not need to be managed by programmers in MRC. Therefore, some memory management methods should be overwritten.
The implementation part is the same as that of the ARC. You only need to overwrite some memory management methods in MRC: *-(id) retain. you do not need to add reference counters in a single instance. returnself. *-(id) autorelease. only objects in the heap are required. not required in the Singleton. returnself. *-(NSUInteger) retainCount. (writable or not, to prevent misunderstanding ). you do not need to modify the reference count in a single example. Return the largest unsigned integer. return UINT_MAX; *-(oneway void) release. release is not required. directly overwrite the data, and the life is not done.
# Import "XNShareTool. h "@ implementation XNShareToolstatic XNShareTool * _ instance; + (id) allocWithZone :( struct _ NSZone *) zone {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {_ instance = [super allocWithZone: zone] ;}); return _ instance ;}+ (instancetype) sharedTool {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {_ instance = [[XNShareTool alloc] init] ;}); return _ instance ;}- (id) copyWithZone :( NSZone *) zone {return _ instance ;} # method to be overwritten in pragma mark-MRC // No counter + 1-(id) retain {return self;} // No. only objects in the heap need-(id) autorelease {return self;} // No-(oneway void) release {} // No counter count. directly return the maximum unsigned integer-(NSUInteger) retainCount {return UINT_MAX; // refer to the retainCount of the string in the constant area} @ end

Iii. Integration of ARC and MRC
Integration is to facilitate the use of a single instance in both ARC and MRC. Instead of modifying the method in the Singleton.
The specific method is to use macro definition: (to determine whether the ARC environment is used, the memory management method is omitted if yes)

# If! _ Has_feature (objc_arc)

Put the memory management method in MRC in this place

# Endif

The Code is as follows:

// ============================== ARC/MRC integration ====== ======================================## pragma mark-MRC method To be overwritten, integration of ARC and MRC # if! _ Has_feature (objc_arc)-(id) retain {return self;}-(id) autorelease {return self;}-(oneway void) release {}-(NSUInteger) retainCount {return UINT_MAX ;} # endif // ========================================== ==========================================================


Reprinted please indicate the source: http://blog.csdn.net/xn4545945






How to Use the IOS Singleton mode ?? The Singleton mode of all programming languages is similar to that of Object-c, Java, C ++, and so on. It has little to do with the language, but it has something to do with the syntax.

IOS has a false class: to define a singleton for AccountManager, perform the following steps:

The. h file should have a similar definition:
+ (Id) sharedInstance;

Ii. classes in the. m file should be defined below:

// Declare the global only static object and the AccountManager type
Static AccountManager * _ sharedInstance;
// Method implementation
+ (Id) sharedInstance {
@ Synchronized ([AccountManagerclass]) {
If (_ sharedInstance = nil ){
_ SharedInstance = [[AccountManageralloc] init];
}
}
Return_sharedInstance;
}

3. Use this Singleton for other class objects and call a method of this Singleton (todoSomething ):
[[AccountManager sharedInstance] todoSomething];

Additional instructions:
1. sharedInstance name I used to use aliases. In short, keep the AccountManager class as a whole. Only instances can be created during the running of the application.
2. Examples are provided to implement the lazy singleton. In addition, the singleton method also completes the task.
How to Use Singleton ios in development

Basic Concepts
Single-instance mode common software design mode core structure only contains special classes called single-instance type ensure that only instances of the system class are in the single-instance mode and the instance is easy to access
Ii. IOS Singleton Mode
1. Creating an object will consume resources of multiple systems. In this case, the single-instance mode saves alloc time because you only need instances.
2. for IOS developers, multiple modules must use the same variable. When this variable is put into the singleton class, it becomes easy for all the calls to access this variable. Otherwise, the variables can only be passed to other modules through the module, increasing the risk and complexity.
3. Basic Steps for creating the singleton Mode
1. Declare the static instance of the singleton object and initialize nil
2. Declare the class factory method to generate the class instance and only generate
3. overwrite the allcoWithZone method to ensure that unnecessary objects are generated during alloc.
4. Implement the NSCopying protocol to overwrite the release, autorelease, retain, and retainCount methods to ensure that only instantiated objects are available.
5. Pay attention to using the @ synchronized keyword in a multi-threaded Environment

[Cpp] view plaincopyprint?
//
// UserContext. h
// SingleDemo
//
// Created by andyyang on 9/30/13.
// Copyright (c) 2013 andyyang. All rights reserved.
//

# Import <Foundation/Foundation. h>

@ Interface UserContext: NSObject
@ Property (nonatomic, retain) NSString * username;
@ Property (nonatomic, retain) NSString * email;
+ (Id) sharedUserDefault;
@ End

[Cpp] view plaincopyprint?
//
// UserContext. m
// SingleDemo
//
// Created by andyyang on 9/30/13.
// Copyright (c) 2013 andyyang. All rights reserved.
//

# Import "UserContext. h"

Static UserContext * singleInstance = nil;
@ Implementation UserContext

+ (Id) sharedUserDefault
{
If (singleInstance = nil)
{
@ Synchronized (self)
{
If (singleInstance = nil)
{
SingleInstance = [[self class] alloc] init];

}
}
}
Return singleInstance;
}

+ (Id) allocWithZone :( NSZone *) zone;
{
NSLog (@ "HELLO ");
If (singleInstance = nil)
{
SingleInstance = [super allocWithZone: zone];
}
Return singleInstance;
}
-(Id) copyWithZone :( NSZone *) zone
{
NSLog (@ "hello ");
Return singleInstance;
}
-(Id) retain
{
Return singleInstance;
}
-(Oneway void) release

{
}
-(Id) autorelease
{
Return singleInstance;
}

-(NSUInteger) retainCount
{
Return UINT_MAX;
} @ End

[Cpp] view plaincopyprint?
# Import <Foundation/Foundation. h>
# Import "UserContext. h"

Int main (int argc, const char * argv [])
{

@ Autoreleasepool {

UserContext * userContext1 = [UserContext sharedUserDefault];
UserContext * userContext2 = [UserContext sharedUserDefault];
UserContext * userContext3 = [[UserContext alloc] init];
UserContext * userContext4 = [userContext1 copy];
// Insert code here...
NSLog (@ "Hello, World! ");

}
Return 0;
}

We use the methods provided by ios to implement the singleton mode:

SYNTHESIZE_SINGLETON_FOR_CLASS (MyClassName );

This statement is placed in the @ implementation MyClassName declaration sample class and will automatically become a singleton

Content from richard _ Feng's blog

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.