iOS development Multithreading-single-case mode (ARC)-Top of text

Source: Internet
Author: User

Original http://www.cnblogs.com/wendingding/p/3808641.html

iOS Development multithreaded article-singleton mode (ARC)

First, simple description:

Design Patterns: Years of software development, summed up a set of experience, methods and tools

There are 23 design patterns in Java, the most common in iOS is the singleton mode and the proxy mode.

Second, the single case mode description

(1) The role of the singleton mode: can guarantee in the program running process, a class has only one instance, and the instance is easy for outside access, so as to conveniently control the number of instances, and save system resources.

(2) The use of Singleton mode: in the entire application, share a resource (this resource only need to create initialization 1 times), should let this class created by the object is always only one.

(3) The pattern of Singleton is different in the ARC\MRC environment, it is necessary to write 2 different sets of code

You can use a macro to determine whether an arc environment

#if// ARC#Else// MRC#endif        

(4) in Arc, the realization of the singleton mode

Retains a global static instance of static ID _instance in. m;

1) Rewrite Allocwithzone: method, create a unique instance here (Note thread safety)

1 + (ID)allocwithzone: (struct _nszone *) Zone2 {    @synchronized (self) {if (!_instance) {4 _ instance = [Allocwithzone:zone];  5}6}return _instance;           

2) provides 1 class methods for accessing unique instances of the outside world

1 + (Instancetype) Sharedsoundtool2 {3     @synchronized (self) {if (!_instance) {5 _instance = [ [Selfalloc] init]; 6} 7} return _instance; 9}          

3) Implement Copywithzone: Method

1 + (ID) copywithzone: (struct _nszone *) Zone2 {3     return _instance;  4}    

(5) Non-arc (MRC), single-instance mode implementation (several steps more than ARC)

Implementing a memory management approach

-(ID) retain {return self;}

-(Nsuinteger) Retaincount {return 1;}

-(OneWay void) Release {}

-(ID) autorelease {return self;}

Three, single-case mode (ARC)

1. Description

Override Allocwithzone: Method to control memory allocation. Because the method is called internally by Alloc, each time the Allocwithzone: method is called, the system creates a new memory space.

Alloc method: Always allocate memory only once

Init method: Ensure that all MP3 data is loaded only once.

2. Code examples

Create an audio tool class that inherits the child NSObject class.

Implement the following code in this class to observe:

 1//2//yyaudiotool.m3//06-Single Case Mode 14//5//Created by Apple on 14-6-25.6//Copyright (c) 2014 itcase. All rights reserved.7//87 mImport"YYAudioTool.h "Ten @interface Yyaudiotool ()11//Used to save MP3 files12@property (Nonatomic,strong) nsmutabledictionary *muscis;@end@implementation Yyaudiotool15//Construction method-(ID) init17 {18if (self=[Super Init]) {19//Load the required music resources20//....21st//Self.muscis=[nsmutabledictionary dictionary];22//self.muscis[@ "1.mp3"]=1mp3 data;23//self.muscis[@ "2.mp3"]=2mp3 data;24}25return self;26}2728//Two methods of invocation29 + (ID) alloc30 {31 NSLog (@ " Span class= "string" >alloc----"); 32 return [super alloc]; }34 35 // control memory allocations, Each time the Allocwithzone: method is called, the system creates a new memory space 36 + (ID) allocwithzone: (struct _nszone *) zone 37 {38 NSLog (@ "39 return [super allocwithzone:zone];40}41 42 43 44 @end  

In the host controller, create the tool class object:

 1//2//Yyviewcontroller.m3//06-Single Case Mode 14//5//Created by Apple on 14-6-25.6//Copyright (c) 2014 itcase. All rights reserved.7//87 mImport"YYViewController.h "10 #Import"YYAudioTool.h "1112 @interface yyviewcontroller () 13 14 @end 15 16 @implementation yyviewcontroller17 18-(void) viewdidload19 {20 [super viewdidload]; 21 Yyaudiotool *tool1=[[yyaudiotool Alloc]init]; 22 Yyaudiotool *tool2=[[yyaudiotool Alloc]init]; 23 Yyaudiotool *tool3=[[yyaudiotool Alloc]init]; 24 Yyaudiotool *tool4=[[yyaudiotool Alloc]init]; 25 NSLog (@ "%p--%p--%p--%p", Tool1,tool2,tool3, TOOL4); 26} 27 28 @end          

Printing results:

Note: In Alloc, the lower-level method is called to allocate memory space in the Allocwithzone method, and the code above creates four different objects.

3. Singleton mode: Design ideas

(1) Always allocate only one piece of memory to create objects

(2) Provides a class method that returns a unique internal variable

(3) It is best to ensure that the Init method is initialized only once

code example:

Create an audio tool class that inherits the child NSObject class.

In this class, the following code is implemented according to the design idea:

YYAUDIOTOOL.M file

 1//2//yyaudiotool.m3//06-Single Case Mode 14//5//Created by Apple on 14-6-25.6//Copyright (c) 2014 itcase. All rights reserved.7//89 #Import"YYAudioTool.h "Ten @interface Yyaudiotool ()11//Used to save MP3 files12@property (Nonatomic,strong) nsmutabledictionary *muscis;@end14@implementation Yyaudiotool16//Define a variable (only one copy of the whole process)17Static ID _instace;18//Single-case mode: Design19//(1) Always allocate only one piece of memory to create objects20//(2) Provides a class method that returns a unique internal variable21st//(3) It is best to ensure that the Init method is initialized only once2223//Construction method-(ID) init25 {26//__block ID Obj=nil;27Static ID Obj=nil;28Static dispatch_once_t Oncetoken;Dispatch_once (&oncetoken, ^{30if ((obj=[Super init]) = nil) {31//Load the required music resources32//....33//Self.muscis=[nsmutabledictionary dictionary];34//self.muscis[@ "1.mp3"]=1mp3 data;35//self.muscis[@ "2.mp3"]=2mp3 data;36}37});Self=obj;3940return self;41}424344//Override this method to control the allocation of memory, always allocating only one storage space at a time+ (ID) allocwithzone: (struct _nszone *) zone46 {4748//The code inside will only execute once.49Static dispatch_once_t Oncetoken;Dispatch_once (&oncetoken, ^{Wuyi _instace=[Super Allocwithzone:zone];52});53return _instace;54} 55 56 // class method 57 + (ID) sharedaudiotool58 {59 //60 static dispatch_once_t Oncetoken; 61 dispatch_once (&oncetoken, ^{62 _instace=[[self Alloc]init];63}); 64 return _instace; }66 67 + (ID) copywithzone: (struct _nszone *) Zone68 {69 return _instace; }71 @end            

YYAudioTool.h file

1 #Import <Foundation/Foundation.h>3 @interface yyaudiotool:nsobject// provides a class method that returns an internally unique variable 5 + (ID) sharedaudiotool; 6 @end     

Create objects in the host controller:

 1//2//Yyviewcontroller.m3//06-Single Case Mode 14//5//Created by Apple on 14-6-25.6//Copyright (c) 2014 itcase. All rights reserved.7//89 #Import"YYViewController.h "10 #Import"YYAudioTool.h "11@interface Yyviewcontroller ()13@end15@implementation Yyviewcontroller1718-(void) viewdidload19 {20 [ Super Viewdidload]; 21 // Yyaudiotool *tool1=[[yyaudiotool Alloc]init ]; 22 // Yyaudiotool *tool2=[[yyaudiotool Alloc]init ]; 23 Yyaudiotool *tool1=[yyaudiotool Sharedaudiotool]; 24 Yyaudiotool *tool2=[yyaudiotool Sharedaudiotool]; 25 Yyaudiotool *tool3=[[yyaudiotool Alloc]init]; 26 Yyaudiotool *tool4=[[yyaudiotool Alloc]init]; 27 NSLog (@ "%p--%p--%p--%p", Tool1,tool2,tool3, TOOL4); 28} 29 30 @end          

To observe the printed result:

Description: Only one instance of an object is created throughout the program.

4.static Supplement:

Note: Static ID instace=nil; and static ID instace;instace=nil; the difference

iOS development Multithreading-single-case mode (ARC)-Top of text

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.