#import "ApplicationSupport.h" static ApplicationSupport *support = nil; @implementation ApplicationSupport + (ApplicationSupport *)sharedSupport { //加锁使之线程安全 @synchronized(self){ if(support == nil){ support = [[ApplicationSupport alloc]init]; } } return support; } //重写NSObject中的此方法,相当于重写了alloc + (id)allocWithZone:(struct _NSZone *)zone { if(support == nil){ support = [super allocWithZone:zone]; return support; } return nil; } - (id)copyWithZone:(NSZone *)zone { return self; } //此类是一个单例类,这个类的对象只能有一个 #import <Foundation/Foundation.h> @interface ApplicationSupport : NSObject <NSCopying> //提供一个类方法,返回那个唯一的对象 + (ApplicationSupport *)sharedSupport; int main(int argc, const char * argv[]) { ApplicationSupport *a1 = [[ApplicationSupport alloc]init]; //ApplicationSupport *a2 = [[ApplicationSupport alloc]init]; //ApplicationSupport *a1 = [ApplicationSupport sharedSupport]; ApplicationSupport *a2 = [ApplicationSupport sharedSupport]; ApplicationSupport *a3 = [a1 copy]; NSLog(@"%p, %p, %p", a1, a2, a3); return 0; }
原文:http://my.oschina.net/u/2447084/blog/522232