在Objective-C中,视图控制器(UIViewController)设置通知监听通常涉及到以下几个步骤:
1. 首先,你需要创建一个NSNotification的发布者,这通常是某个特定的行为或状态改变的地方,比如一个服务、另一个控制器或者数据模型。
```objective-c
// 假设有个名为`sharedManager`的服务对象
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationReceived:) name:@"MyCustomNotification" object:nil];
```
2. 在这里,`self`是接收者,也就是你的视图控制器,`notificationReceived:`是你定义的一个处理方法,用来响应接收到的通知。
```objective-c
- (void)notificationReceived:(NSNotification *)notification {
// 在这个方法中处理通知的内容
id userInfo = notification.userInfo;
// ... 进行相应的操作
}
```
3. 当你想取消监听时,记得在适当的时候移除通知观察者,如视图控制器即将销毁或不再需要监听:
```objective-c
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"MyCustomNotification" object:nil];
}
```