1 //定义一个静态对象,保证整个程序中都存在 2 static Person *_instance = nil; 3 //程序一启动就加载分配内存 4 + (void) load{ 5 NSLog(@"启动加载"); 6 _instance = [[self alloc] init]; 7 } 8 //初始化方法 9 + (void) initialize{ 10 NSLog(@"init初始化方法"); 11 } 12 //定义类工厂方法,以后每次调用类工厂方法时都会返回同一个内存空间 13 + (instancetype) sharedPerson{ 14 NSLog(@"类工厂方法"); 15 return _instance; 16 } 17 //重写alloc方法 18 + (instancetype) alloc{ 19 if (_instance != nil) { 20 //抛出一个异常 21 NSException *exp = [NSException exceptionWithName:@" NSInternalInconsistencyException" reason:@" There can only be one UIApplication instance." userInfo:nil]; 22 [exp raise]; 23 } 24 NSLog(@"alloc调用”); 25 // 调用父类方法, 程序启动时调用 26 return [super alloc]; 27 }
原文:http://www.cnblogs.com/JL-609/p/4955097.html