Iphone 来自特定对象的Post通知-cocoa touch
所以我在Iphone 来自特定对象的Post通知-cocoa touch,iphone,objective-c,cocoa-touch,notifications,Iphone,Objective C,Cocoa Touch,Notifications,所以我在NotificationManager类中有这个函数 -(void) postNotificationForClassName:(NSString*)className withObjects:(NSArray*)objects withError:(BOOL)withError { notificationName = [NSString stringWithFormat:@"didLoad%@",className]; [[NSNotificationCente
NotificationManager
类中有这个函数
-(void) postNotificationForClassName:(NSString*)className withObjects:(NSArray*)objects withError:(BOOL)withError
{
notificationName = [NSString stringWithFormat:@"didLoad%@",className];
[[NSNotificationCenter defaultCenter]
postNotificationName:notificationName object:self];
}
现在,假设我有两个班,A和B
从A的方法foo()中,我执行以下操作:
[[NotificationManager sharedManager]
postNotificationForClassName:@"A" withObjects:objects withError:NO]
[[NotificationManager sharedManager]
postNotificationForClassName:@"A" withObjects:objects withError:NO]
从B的方法goo()中,我执行以下操作:
[[NotificationManager sharedManager]
postNotificationForClassName:@"A" withObjects:objects withError:NO]
[[NotificationManager sharedManager]
postNotificationForClassName:@"A" withObjects:objects withError:NO]
现在,我很好奇,如果我只想听A类发布的通知,我该怎么办
这样行吗
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(didLoadData:)
name:@"didLoadA" object:classAObject];
因为我想当我打电话的时候
[[NSNotificationCenter defaultCenter]
postNotificationName:notificationName object:self];
我传递了“self”,那么“self”将是NotificationManager
,而不是调用NotificationManager
方法的A类或B类
我在这里是对还是错?如果我是对的,有没有办法实现我想实现的目标
谢谢
self
是一个特殊变量,总是指接收当前正在处理的消息的对象。在NotificationManager
的-postNotificationForClassName:withObjects:withError:withError:withError:
中,self
是NotificationManager
(或其后代)。至于调用-addObserver:…
中的self
,这取决于调用发生在哪个方法中
正如您所注意到的,-addObserver:…
允许您监视来自特定对象的通知。如果将类A
用作对象,则可以使用此选项监视来自A
s的消息:
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(didLoadData:)
name:@"didLoadA" object:[A class]];
但是,您还需要在-postNotificationForClassName:withObjects:objectswithError:withError:
中更改通知发件人
-(void)postNotificationForClassName:(NSString*)className
withObjects:(NSArray*)objects
withError:(BOOL)withError
from:(id)sender
{
notificationName = [NSString stringWithFormat:@"didLoad%@",className];
[[NSNotificationCenter defaultCenter]
postNotificationName:notificationName object:[sender class]];
}
您是想在
-goo
中传递@“A”作为类名吗?(方法名称不包括括号。)是的,我做了,只是为了示例显示来自两个不同类(A和B)的相同通知,所以,有没有办法让某些观察者只从类A获取通知?这意味着foo()会弹出他的通知处理程序,而goo()不会。@Idan:这取决于对我上述澄清请求的回答。同时回答:)