Implementation of the OC Singleton mode and the OC Mode

Source: Internet
Author: User

Implementation of the OC Singleton mode and the OC Mode

SingleClass. m

# Import <Foundation/Foundation. h> @ class SingleClass; static SingleClass * instance = nil; @ interface SingleClass: NSObject <NSCopying> + (instancetype) using instance; @ end @ implementation SingleClass // class method, obtain the singleton object + (instancetype) using instance {if (! Instance) {instance = [[self alloc] init];} return instance;} // class method. An existing Singleton + (instancetype) is returned when the alloc method of the object is called) allocWithZone :( struct _ NSZone *) zone {if (! Instance) {instance = [super allocWithZone: zone];} return instance;} // copy, returns the existing Singleton-(id) copyWithZone :( NSZone *) zone {return instance;} // copy, returns an existing Singleton-(id) copy {return instance;} @ end

Main. m

int main(int argc, const char * argv[]) {    @autoreleasepool {        SingleClass *s1 = [SingleClass shareInstance];        SingleClass *s2 = [SingleClass shareInstance];        SingleClass *s3 = [[SingleClass alloc] init];        SingleClass *s4 = [s1 copy];                NSLog(@"%p",s1);        NSLog(@"%p",s2);        NSLog(@"%p",s3);        NSLog(@"%p",s4);    }    return 0;}

Result:

2015-03-22 22:24:21.201 SingleDemo[1349:61326] 0x1001066e02015-03-22 22:24:21.202 SingleDemo[1349:61326] 0x1001066e02015-03-22 22:24:21.202 SingleDemo[1349:61326] 0x1001066e02015-03-22 22:24:21.202 SingleDemo[1349:61326] 0x1001066e0

 

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.