使用NSNotificationCenter 事件通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onFuckme:) name:strFuckMe object:nil];
第一个参数是要接收Notification的对象,第二个参数是响应函数,第三个是通知的名称,第四个参数表示接收哪个发送者的通知,如果第四个参数为nil,接收所有发送者的通知。
(2)既然init里面注册了这个通知,那么就需要在dealloc里面移除这个通知的注册:
代码如下:
[[NSNotificationCenter defaultCenter] removeObserver:self name:strFuckMe object:nil];
(3)怎么发送Notification通知呢?
代码如下:
如果不需要传递参数的通知:
[[NSNotificationCenter defaultCenter] postNotificationName:strFuckMe object:nil];
如果要传递参数的通知:
SFuckRet sFuckRet;
NSValue* value = [NSValuevalueWithBytes:&sFuckRetobjCType:@encode(SFuckRet)];
[[NSNotificationCenter defaultCenter] postNotificationName:strFuckMe object:nil userInfo:[NSDictionarydictionaryWithObjectsAndKeys:value,@"value",nil]];
SFuckRet是一个定长的结构体对象,所以需要用NSValue来包装以下,才能放到Object-c的容器中。
postNotificationName参数是要发送的通知的名字,object:参数是一个id,一般可以传递self,可以让接收通知者能调用的发送通知者。
userInfo是一个NSDictionary可以传递自己的其他信息。一般数据都放在这个里面。
注意一般NSValue一般用来包装定长的结构体,CGRect,CGPoint什么的,千万不能包含指针之类的东西。
(4)如何处理通知呢?
代码如下:
- (void)onFuckme:(NSNotification*)notification
{
NSDictionary* user_info = [notification userInfo];
NSValue* value = [user_info objectForKey:@"value"];
SFuckRet sfuckRet;
[value getValue:&sfuckRet];
}
NSDictionary* user_info = [notification userInfo]; 这句代码就是取出PostNitifycation的时候设置的NSDictionary信息。
这样就取出来了所要传递的结构体啦。