目錄
- 觀察者 (NSNotification)
- 委托模式 (Delegate)
- 單例 (Single)
- MVC
一仿滔、觀察者 (NSNotification)
觀察者設(shè)計(jì)模式就像微信公眾號一樣毁欣,你關(guān)注了一個(gè)公眾號廓旬,才能收到公眾號發(fā)的消息,所以說addObserver注冊消息通知是前提疆瑰,只有先注冊消息通知陵霉,才能收到相應(yīng)post的消息。
// 注冊一個(gè)登陸成功的通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginSucceed) name:NFLoginSucceedNotification object:nil];
注冊完這個(gè)通知后炸枣,不管你是賬號登錄,還是注冊完直接登錄弄唧,還是第三方登錄成功的時(shí)候适肠,都可以post一個(gè)登陸成功的通知。
// 登錄成功的通知
[[NSNotificationCenter defaultCenter]postNotificationName:NFLoginSucceedNotification object:nil];
通知使用起來比較簡單就不多介紹了候引,以下是通知的幾點(diǎn)說明:
- 通知的名字盡量使用常量字符串
// 登錄成功
UIKIT_EXTERN NSString *const NFLoginSucceedNotification;
- 通知的執(zhí)行順序迂猴,是按照post的順序執(zhí)行的,并且是同步操作的背伴,即如果你在程序中的A位置post了一個(gè)NSNotification,在B位置注冊了一個(gè)observer,通知發(fā)出后傻寂,必須等到B位置的通知回調(diào)執(zhí)行完以后才能返回到A處繼續(xù)往下執(zhí)行息尺,所以不能濫用通知。
- 善于用系統(tǒng)提供給我們的通知疾掰,比如:
UIKIT_EXTERN NSNotificationName const UIKeyboardWillShowNotification __TVOS_PROHIBITED;
UIKIT_EXTERN NSNotificationName const UIKeyboardDidShowNotification __TVOS_PROHIBITED;
UIKIT_EXTERN NSNotificationName const UIKeyboardWillHideNotification __TVOS_PROHIBITED;
UIKIT_EXTERN NSNotificationName const UIKeyboardDidHideNotification __TVOS_PROHIBITED;
4.通知發(fā)出后搂誉,controller不能從觀察者獲得任何的反饋信息,這也通知和委托模式 (Delegate)的一個(gè)區(qū)別吧静檬。
5.NSNotification與多線程問題炭懊,在多線程應(yīng)用中,Notification在哪個(gè)線程中post拂檩,就在哪個(gè)線程中被轉(zhuǎn)發(fā)侮腹,而不一定是在注冊觀察者的那個(gè)線程中。也就是說稻励,Notification的發(fā)送與接收處理都是在同一個(gè)線程中父阻。
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"addObserver notification thread = %@",[NSThread currentThread]);
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification) name:HandleNotificationName object: nil];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:HandleNotificationName object:nil];
NSLog(@"post notification thread = %@",[NSThread currentThread]);
});
}
- (void)handleNotification
{
NSLog(@"handle notification thread = %@",[NSThread currentThread]);
}
其打印結(jié)果如下:
addObserver notification thread = <NSThread: 0x60000007be00>{number = 1, name = main}
handle notification thread = <NSThread: 0x600000267200>{number = 3, name = (null)}
post notification thread = <NSThread: 0x600000267200>{number = 3, name = (null)}