iOS中的单例模式
单例模式即意味着整个程序中该类的对象只分配一次内存,以后创建的该类的对象占据的都是同一个内存空间,系统的UIApplication对象为单例模式,大致分析如下:
- 提供share类工厂方法(类工厂方法格式:shared + 类名)
- 程序一启动便创建单例:在+ (void) load类方法中创建单例并分配内存空间
- 不允许系统调用alloc方法,一旦调用便抛出异常:重写alloc方法,判断后抛出异常
- 定义静态变量static修饰实例化对象,保证整个应用程序中单例都存在
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 }
+ (void) load 方法:程序一启动,无论有没有使用到该类,都会调用该方法,且只调用一次+ (void) initialize方法:使用到该类时就会调用该方法,且只会调用一次,以后再使用时不再调用

浙公网安备 33010602011771号