Catalogue iOS () multi-thread network-GCD ordering example design mode, iosgcd

Source: Internet
Author: User

Catalogue iOS () multi-thread network-GCD ordering example design mode, iosgcd

CAT/CAT sharing, must be excellent

For Original Articles, please reprint them. Reprinted Please note: Yan Nai-yu's blog
Http://blog.csdn.net/u013357243? Viewmode = contents

Singleton Mode 1: The Role of Singleton Mode

It can ensure that there is only one instance for a class during the program running, and the instance is easy for external access.
This allows you to easily control the number of instances and save system resources.

Use Cases of Singleton Mode
Share a resource in the entire application (this resource only needs to be created and initialized once)

Simply put, I have a tool class, and I have a file. For example, I have designed a music player, NYPlayer. I want to have one of these players. This is a singleton, when I use it, I only need to let the player work. If there are multiple players, I don't know which one to specify, or if there are duplicates, a bug will occur.
Baidu encyclopedia says this: The Singleton model is a common software design model. Its core structure only contains a special class called Singleton class. The Singleton mode ensures that there is only one instance in a class in the system and the instance is easy to access, so as to conveniently control the number of instances and save system resources. If you want to have only one class object in the system, the singleton mode is the best solution.
To put it simply, only one object exists in a class.

2: Implementation of Singleton mode in ARC

Process:
Keep a Global static instance in. m.
Here we need to use static. Remember him. I will write back a blog about static keywords later.

static id _instance;

Override allocWithZone: method to create a unique instance (pay attention to thread security)
When the [class name alloc] method is called during class creation, the allcWithZone method is automatically called internally to load a space. Therefore, we only need to override this method, when the global variable instance we define is worthwhile, it will be directly returned. If not, the parent class method [super allocWithZone: zone] will be called and assigned to the instance, but there is a danger at this time, that is, if two threads come in, it will be allocated twice, so we need to lock this program.

+ (Id) allocWithZone :( struct _ NSZone *) zone {if (_ instance = nil) {// prevent frequent lock @ synchronized (self) {if (_ instance = nil) {// prevent multiple _ instance = [super allocWithZone: zone] ;}} return _ instance ;}

Provides a class method for external access to a unique instance.
The same as allocWithzone, but the difference is that the [self alloc] init] method is called here.

+ (Instancetype) sharedMusicTool {if (_ instance = nil) {// prevent frequent lock @ synchronized (self) {if (_ instance = nil) {// prevent multiple times from being created _ instance = [[self alloc] init] ;}}return _ instance;} copyWithZone: method-(id) copyWithZone :( struct _ NSZone *) zone {return _ instance ;}
3: single-instance mode in MRC

Process:
Non-ARC (MRC), Singleton mode implementation (several more steps than ARC)
Memory management method.

-(Id) retain {return self;} // The counter + 1 in the parent class, And the rewrite will not + 1-(NSUInteger) retainCount {return 1 ;} // return the count of the current object in the parent class-(oneway void) release {} // counter-1 in the parent class, and no-1-(id) will be returned for rewriting) autorelease {return self;} // the memory in the parent class is automatically managed and released, which is related to the memory pool.
Use the perfect Singleton mode (ARC & MRC) in GCD to judge the macro of ARC

First, we need to know a macro _ has_feature (objc_arc)

The Singleton mode varies in the ARC \ MRC environment and requires two sets of different codes.
Macro can be used to determine whether the ARC environment is used.

#if __has_feature(objc_arc)// ARC#else// MRC#endif
Macro for transferring values

Just one sentence

#define NYSingletonH(name) + (instancetype)shared##name;

The name will be automatically replaced by the name.

Use GDC to run code once

How can this problem be solved? It is actually a one-time code to replace the lock with GCD.

The Code is as follows:

+(id)allocWithZone:(struct _NSZone *)zone    {        if (_instance == nil) {            static dispatch_once_t onceToken;            dispatch_once(&onceToken, ^{                if (_instance == nil) {                    _instance = [super allocWithZone:zone];                }            });        }        return _instance;    }

Shortcut: In xcode, you only need to press dispatch_once. enter it.

In the final way, you don't need to knock on the code for a single example in the future. Just drop it.

Step 1: Resume A. H file, such

Step 2: Write the following code into the file:

//. H file # define NYSingletonH (name) + (instancetype) shared # name ;//. m file # define NYSingletonM # if _ has_feature (objc_arc) # define NYSingletonM (name) \ static id _ instance; \\+ (id) allocWithZone :( struct _ NSZone *) zone \ {\ if (_ instance = nil) {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^ {\ if (_ instance = nil) {\ _ instance = [super allocWithZone: zone] ;\}\}) ;\}\ return _ instance ;\}\+ (instancetype) shared # name \ {\ if (_ instance = nil) {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^ {\ if (_ instance = nil) {\ _ instance = [[self alloc] init] ;\}\}) ;\}\ return _ instance ;\}\\-(id) copyWithZone :( NSZone *) zone \ {\ return _ instance; \\}# else # define NYSingletonM (name) \ static id _ instance; \\+ (id) allocWithZone :( struct _ NSZone *) zone \ {\ if (_ instance = nil) {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^ {\ if (_ instance = nil) {\ _ instance = [super allocWithZone: zone] ;\}\}) ;\}\ return _ instance ;\}\+ (instancetype) shared # name \ {\ if (_ instance = nil) {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^ {\ if (_ instance = nil) {\ _ instance = [[self alloc] init] ;\}\}) ;\}\ return _ instance ;\}\\-(id) copyWithZone :( NSZone *) zone \ {\ return _ instance; \} \-(id) retain \ {\ return self ;\}\-(NSUInteger) retainCount {return 1 ;} \-(oneway void) release {}\-(id) autorelease {return self ;}# endif

The \ symbol is used to include the following stuff in the previous line, because define can only define one row.

Step 3: Write the call code in the pch file:

#import "NYSingleton.h"

Step 4: Call in the class to be used:

Call this in the dot H file

Call this in the dot m file

The final call is still a singleton:

Supplement: the custom macro replaces NSLog.

Note: during the development process, NSLog is used to print the information for debugging, but the releae software cannot contain NSLog, which may lead to the risk of being rejected, however, it would be too painful to comment out all nslogs, which is not conducive to future debugging.

Next, we can use a custom macro to replace NSLog, and only output

/* In XCode llvm xxx-Preprocessing, the Debug = 1 flag is added to DEBUG */# ifdef DEBUG # define NSLog (FORMAT ,...) fprintf (stderr, "% s: % d \ t % s \ n", [[NSString stringwithuf8string :__ FILE _] lastPathComponent] UTF8String], _ LINE __, [[NSString stringWithFormat: FORMAT, ##__ VA_ARGS _] UTF8String]); # else # define NSLog (FORMAT ,...) nil # endif

Paste the above Code into the ProjectName-Prefix.pch file.

During debugging, logs (in the format of File Name: row number) are output.

The log output is disabled when the Release official version is released.

Because the Debug = 1 flag is added in XCode llvm xxx-Preprocessing. Of course, we can also change DEBUG to number 1.

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.