Objective-C in IOS: learning the singleton mode in ARC, iosobjective-c

Source: Internet
Author: User

Objective-C in IOS: learning the singleton mode in ARC, iosobjective-c

The Singleton mode is a commonly used design mode. The most common purpose is to save and transmit data. This is due to the features of the singleton mode. First, let me briefly introduce the features of Singleton mode.

Three features of Singleton mode:

1. A class can only have one instance;

2. It must create the instance on its own;

3. It must provide this instance to the entire system.

The Code is as follows:

MySingleton. h

# Import <Foundation/Foundation. h>

 

@ Interface mySingleton: NSObject

+ (MySingleton *) sharedInstance;

@ End

 

MySingleton. m

# Import "mySingleton. h"

Static mySingleton * myst = nil;

@ Implementation mySingleton

+ (MySingleton *) sharedInstance {

If (myst = nil ){

Static dispatch_once_t once;

Dispatch_once (& once, ^ {

Myst = [[super allocWithZone: NULL] init];

});

}

Return myst;

}

+ (Id) allocWithZone :( struct _ NSZone *) zone {

Return [mySingleton sharedInstance];

}

-(Id) copy {

Return [mySingleton sharedInstance];

}

@ End

This mySingleton class is created with a static modified myst global instance, which is a singleton instance.

 

Implementation Method:

-(Void) viewDidLoad {

[Super viewDidLoad];

MySingleton * s1 = [mySingleton sharedInstance];

MySingleton * s2 = [[mySingleton alloc] init];

MySingleton * s3 = [s1 copy];

NSLog (@ "s1 =%@", s1 );

NSLog (@ "s2 = % @", s2 );

NSLog (@ "s3 =%@", s3 );

}

Running result:

S1 = <mySingleton: 0x7fbea8e05d70>

S2 = <mySingleton: 0x7fbea8e05d70>

S3 = <mySingleton: 0x7fbea8e05d70>

The running result shows that the addresses of the objects generated by the three different methods are the same.

 

 

 

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.