iOS 通知的基本用法
来源:互联网 发布:诺基亚s40v3软件下载 编辑:程序博客网 时间:2024/05/17 03:51
NSNotification* notification = [NSNotification notificationWithName:kImageNotificationLoadFailed(connection.imageURL)
object:self
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:error,@"error",connection.imageURL,@"imageURL",nil]];
这里需要注意的是,创建自己的通知并不是必须的。而是在创建自己的通知之前,采用NSNotificationCenter类的方法 postNotificationName:object: 和 postNotificationName:object:userInfo:更加便利的发出通知。这种情况,一般使用NSNotificationCenter的类方法defaultCenter就获得默认的通知对象,这样你就可以给该程序的默认通知中心发送通知了。注意:每一个程序都有一个自己的通知中心,即NSNotificationCenter对象。该对象采用单例设计模式,采用defaultCenter方法就可以获得唯一的NSNotificationCenter对象。
2
注册通知:addObserver:selector:name:object:
可以看到除了添加观察者之外,还有其接收到通知之后的执行方法入口,即selector的实参。因此为了进行防御式编程,最好先检查观察者是否定义了该方法。例如:添加观察者代码有
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(aWindowBecameMain:)
name:NSWindowDidBecomeMainNotification object:nil];
这里保证了self定义了aWindowBecameMain:方法。而对于一个任意的观察者observer,不能保证其对应的selector有aWindowBecameMain:,可采用[observer respondsToSelector:@selector(aWindowBecameMain:)]] 进行检查。所以完整的添加观察者过程为:
if([observer respondsToSelector:@selector(aWindowBecameMain:)]) {
[[NSNotificationCenter defaultCenter] addObserver:observer selector:@selector(aWindowBecameMain:) name:NSWindowDidBecomeMainNotification object:nil];
}
注意到addObserver:selector:name:object:不仅指定一个观察者,指定通知中心发送给观察者的消息,还有接收通知的名字,以及指定的对象。一般来说不需要指定name和object,但如果仅仅指定了一个object,观察者将收到该对象的所有通知。
3.发送通知:postNotificationName:object:或者performSelectorOnMainThread:withObject:waitUntilDone:
4 移除通知:
removeObserver:和removeObserver:name:object:
- iOS 通知的基本用法
- iOS 通知的基本用法
- Notification通知的基本用法
- Notification--------通知的基本用法
- iOS NSNotification 通知的用法
- Android中通知的基本用法
- 系统通知Notification的基本用法
- android 通知Notification的基本用法
- 安卓通知的基本用法
- 23读书笔记之通知的基本用法
- IOS本地通知(UILocalNotification)的基本使用
- iOS 通知的基本使用传值
- 通知基本用法NSNotificationCenter
- iOS通知用法
- iOS通知用法
- iOS UILabel的基本用法
- iOS CoreData的基本用法
- ios NSNotFound的基本用法
- hive 2.0 安装配置
- 安卓原生控件SwipeRefreshLayout
- int main(int argc, char **argv)中参数argc与argv的意义
- iOS学习笔记74-IOS多线程知识总结/队列概念/GCD/主队列/并行队列/全局队列/主队列/串行队列/同步任务/异步任务区别附代码
- sed-1
- iOS 通知的基本用法
- ActiveMQ高级特性:VirtualTopic
- block 中使用__weak 和__strong修饰符的问题
- c++中的特化问题
- Spring:源码解读Spring IOC原理
- 四轴飞行器组合导航非线性滤波算法
- 列举MJExtension中的方法
- 【Mac工具箱】独孤九剑!一名全栈设计师的Mac工具箱(设计/开发/效率)
- 微信第三方登录