歡迎關注個人iOS學習總結——天天學一點iOS:https://github.com/practiceqian/one-day-one-iOS-summaryios
iOS中的事件(主要有三類)git
UIResponder(響應者對象)github
iOS中只有繼承了UIResponder的類才能接收並處理事件,稱之爲響應者對象。objective-c
爲何繼承了UIResponder的類都可以接收並處理事件呢?設計模式
//UIResponder類提供瞭如下四個對象方法來處理觸摸事件 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
事件響應鏈安全
全部處理事件響應的類都是UIResponder的子類,響應者鏈是一個由不一樣對象組成的層次結構,其中的每一個對象依次得到響應事件消息的機會,事件將沿着響應者鏈一直向下傳遞,直到該事件被接收而且處理ide
事件的傳遞和響應鏈函數
//事件傳遞是從第一響應者->UIApplication View->ViewController->UIWindow->UIApplication->nil //事件的響應是從UIApplication->FirstResponder UIApplication->UIwindow->ViewController->View
幾種繼承關係性能
事件分發機制學習
UIApplication的幾種狀態
設計原則
iOS開發中幾種經常使用的設計模式
單例模式(兩種實現方法)
//使用@synchronized保證線程安全的懶加載寫法,可是因爲@synchronized是互斥鎖致使性能比較低 + (Singleton *)sharedInstance { @synchronized (self) { if (!instance) { instance = [[Singleton alloc] init]; } } return instance; } //使用GCD中的dispatch_once寫法,同時知足了線程安全和靜態分析器的要求 + (Singleton *)sharedInstance { static dispatch_once_t predicate; dispatch_once(&predicate, ^{ instance = [[Singleton alloc] init]; }); return instance; }
以上兩種單例模式的實現都不能保證SingleTon是惟一的,由於經過[[Single alloc]init]方式建立仍然會建立出新的實例
建立絕對單例的方法
//經過攔截alloc方法來建立絕對單例 //new->alloc //alloc->allocWithZone //alloc方法的內部就是調用了allocWithZone方法,allocWithZone方法的做用就是申請空間建立對象並將建立的對象返回。 + (instancetype)shareInstance { if (instance == nil) { static dispatch_once_t once; dispatch_once(&once, ^{ instance = [[Singleton alloc] init]; }); } return instance; } + (instancetype)allocWithZone:(struct _NSZone *)zone { if (instance == nil) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance = [super allocWithZone:zone]; }); } return instance; }
工廠模式
//一個工廠類須要執行多個方法,能夠將每一個方法衍生出一個類繼承自這個工廠類,實例化工廠類時根據傳入的參數建立對應方法的實例 @implementation OperationFactory + (Operation *) createOperat:(char)operate{ Operation *oper = nil; switch (operate) { case '+': { oper = [[OperationAdd alloc] init]; break; } case '-': { oper = [[OperationSub alloc] init]; break; } case '*': { oper = [[OperationMul alloc] init]; break; } case '/': { oper = [[OperationDiv alloc] init]; break; } default: break; } return oper; } @end
委託模式(這裏只列出使用步驟,A爲委託對象,B爲代理對象)
類A接口爲文件中建立協議,聲明@requeired和@optional方法
類A添加一個屬性,使用weak修飾(不然會形成循環引用)
@property (nonatomic,wead) id<協議名>delegate
類B接口文件/類擴展中遵照協議,並在實現文件中實現協議的required/optional方法
類B中建立一個類A對象,類A對象的delegate設置爲self(類B自身)
在類A對象中調用[self.delegate 方法]
觀察者模式(兩種方式)