iOS 常用设计模式

目录

  • 观察者 (NSNotification)
  • 委托模式 (Delegate)
  • 单例 (Single)
  • MVC
一、观察者 (NSNotification)

观察者设计模式就像微信公众号一样,你关注了一个公众号,才能收到公众号发的消息,所以说addObserver注册消息通知是前提,只有先注册消息通知,才能收到相应post的消息。

// 注册一个登陆成功的通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginSucceed) name:NFLoginSucceedNotification object:nil];

注册完这个通知后,不管你是账号登录,还是注册完直接登录,还是第三方登录成功的时候,都可以post一个登陆成功的通知。

// 登录成功的通知
[[NSNotificationCenter defaultCenter]postNotificationName:NFLoginSucceedNotification object:nil];

通知使用起来比较简单就不多介绍了,以下是通知的几点说明:

  1. 通知的名字尽量使用常量字符串
// 登录成功
UIKIT_EXTERN NSString *const NFLoginSucceedNotification;
  1. 通知的执行顺序,是按照post的顺序执行的,并且是同步操作的,即如果你在程序中的A位置post了一个NSNotification,在B位置注册了一个observer,通知发出后,必须等到B位置的通知回调执行完以后才能返回到A处继续往下执行,所以不能滥用通知。
  2. 善于用系统提供给我们的通知,比如:
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.通知发出后,controller不能从观察者获得任何的反馈信息,这也通知和委托模式 (Delegate)的一个区别吧。

5.NSNotification与多线程问题,在多线程应用中,Notification在哪个线程中post,就在哪个线程中被转发,而不一定是在注册观察者的那个线程中。也就是说,Notification的发送与接收处理都是在同一个线程中。

- (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]);
}

其打印结果如下:

addObserver notification thread = {number = 1, name = main}
handle notification thread = {number = 3, name = (null)}
post notification thread = {number = 3, name = (null)}
二、代理 (Delegate)

你可能感兴趣的:(iOS 常用设计模式)