假设我有classA
这是一类音频,它会多次采样音频输入。
每次class A
获取新数据(可能在第二次发生多次)时,他需要通知另一个班级,classB
。
现在,我可以在class B
中创建classA
的实例,并在有新数据到达时调用B,但这不是模块化软件。
我希望classA
对外界“盲目”,只是为了将他添加到每个项目中,并让另一个classB
将register
他一些如何,所以当A有新的东西,B会知道它,(没有A叫B!)
它如何在目标c中完成?
非常感谢。
答案 0 :(得分:5)
听起来您想要实施Observer Pattern
答案 1 :(得分:3)
您可以在ClassA
中发布通知,并在其他类别(即ClassB
)中注册该通知。
这是你可以做到的:
(在ClassA
中):
[[NSNotificationCenter defaultCenter]
postNotificationName:@"noteName" object:self];
(在ClassB
中):
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(doSomething:)
name:@"noteName" object:nil];
每当ClassA
的实例发布新通知时,将立即通知注册该通知的其他实例。在这种情况下,ClassB
将执行doSomething:(NSNotification *)note
。
[编辑]
您可以通过setter方法(setVar:(NSString*)newVar
)发布该通知。
如果您想传递某些内容,请使用postNotificationName:object:userInfo:
变体。 userInfo
是NSDictionary
,您可以传递任何内容。例如:
NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:var, @"variable", nil];
[[NSNotificationCenter defaultCenter]
postNotificationName:@"noteName" object:self userInfo:dic];
现在,修改您的doSomething:
方法:
-(void)doSomething:(NSNotification*)note {
if ([[note name] isEqualToString:@"noteName"]) {
NSLog(@"%@", [note userInfo]);
}
}
答案 2 :(得分:2)
正如ennuikiller所建议的,在obj-c中实现观察者模式的一种简单方法是使用NSNotificationCenter
类。详情请见see its class reference。
修改强>
另一种方法是使用KVO(键值观察)。这比较复杂但是相对于第一个具有更好的性能。有关简单说明,请参阅Jeff Lamarche blog和KVO Reference。
希望它有所帮助。