用分类, 创建一个UIViewController+notification.h分类, 运用runtime交换成自己方法, 在方法中注册通知. #import "UIViewController+notification.h" #import <objc/runtime.h> @implementation UIViewController (notification) + (void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ // 获得UIViewController的SEL SEL originalSEL = @selector(viewDidLoad); // 要替换的SEL SEL notiSEL = @selector(noti_viewDidLoad); // 方法 Method originalMethod = class_getInstanceMethod([self class], originalSEL); Method notiMethod = class_getInstanceMethod([self class], notiSEL); // 交换两个方法的实现 method_exchangeImplementations(originalMethod, notiMethod); }); } - (void)noti_viewDidLoad { // 这个时候noti_viewDidLoad方法已经被替换了 [self noti_viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification:) name:@"notificationName" object:nil]; } - (void)notification:(NSNotification *)noti { // 可在指定的控制器中, 重写此方法 NSLog(@"%s接收到通知",object_getClassName(self)); } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:@"notificationName" object:nil]; NSLog(@"%s释放通知",object_getClassName(self)); } @end
用分类, 创建一个
UIViewController+notification.h
分类, 运用runtime交换成自己方法, 在方法中注册通知.