標籤:大神 func 類比 告訴 建立 isp 異常類 重寫 name
首先我們得要知道蘋果是如何?單例的:1.不能外界調用alloc,一調用就崩掉,其實就是拋異常(類內部第一次調用alloc就不崩潰,其他都崩潰)。
2.提供一個方法給外界擷取單例。
3.內部建立一次單例,什麼時候建立,程式啟動的時候建立單例。
然後我們來建立一個Person類。
Person.h#import <Foundation/Foundation.h>@interface Person : NSObject// 擷取單例+ (instancetype)sharePerson;@end
Person.m#import "Person.h"@implementation Person// 程式啟動時候建立對象// 靜態變數static Person *_instance = nil;// 作用:載入類// 什麼調用:每次程式一啟動,就會把所有的類載入進記憶體+ (void)load{ NSLog(@"%s",__func__); _instance = [[self alloc] init]; }+ (instancetype)sharePerson{ return _instance;}+ (instancetype)alloc{ if (_instance) { // 標示已經分配好了,就不允許外界在分配記憶體 // 拋異常,告訴外界不運用分配 // ‘NSInternalInconsistencyException‘, reason: ‘There can only be one UIApplication instance.‘ // 建立異常類 // name:異常的名稱 // reson:異常的原因 // userInfo:異常的資訊 NSException *excp = [NSException exceptionWithName:@"NSInternalInconsistencyException" reason:@"There can only be one Person instance." userInfo:nil]; // 拋異常 [excp raise]; } // super -> NSObject 才知道怎麼分配記憶體 // 調用系統預設的做法, 當重寫一個方法的時候,如果不想要覆蓋原來的實現,就調用super return [super alloc];}
在這裡我只是想類比下蘋果底層是如何?單例的,我們一般情況下並不會使用這種方法。我們一般會使用如下方法:
+(instancetype)sharedPerson{ // 靜態變數 static Person *_instance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[self alloc]init]; }); return _instance;}
iOS大神班筆記02-模仿蘋果建立單例