NSNotification 能够发送消息通知,用于记录日志,比如使用 try catch 捕获到异常之后,可以发送通知记录相应的日志,以便后续排查错误。以下代码的功能是添加一个通知,名称是 notificationTest,对应的处理函数是 LogWithNotification,当有通知发送过来时会触发这个函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
- (void)LogWithNotification:(NSNotification *)text{ NSLog(@"-----接收到通知------"); NSString *key = text.userInfo[@"key"]; NSLog(@"%@", key); if ([key isEqualToString:@"exchen"]) { NSString *content = text.userInfo[@"content"]; NSLog(@"%@", content); } } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(LogWithNotification:) name:@"notificationTest" object:nil]; return YES; } |
然后在有需要的地址 post 通知,userInfo 是一个字典,可以用于传递自定义的参数到通知处理函数 LogWithNotification。
1 2 3 4 5 6 7 8 |
//通过通知中心发送通知 NSDictionary *dicUserInfo = [NSDictionary dictionaryWithObjectsAndKeys: @"exchen",@"key", @"error info",@"content", nil]; NSNotification *notification =[NSNotification notificationWithName:@"notificationTest" object:nil userInfo:dicUserInfo]; [[NSNotificationCenter defaultCenter] postNotification:notification]; |