0

可以说我有classA哪一类音频,它对音频输入进行多次采样。每次class A得到一个新数据(秒内可能发生多次),他需要通知另一个类,即classB.

现在,我可以创建一个 in 实例class BclassA在有新数据到达时调用 B,但这不是模块化软件。

我想classA对外界“视而不见”,只是将他添加到每个项目中,并拥有另一个classBregister他有帮助的项目,所以当 A 有新的东西时,B 会知道它,(没有 A 呼叫 B!)

它是如何在目标 c 中正确完成的?

多谢 。

4

3 回答 3

5

听起来你想实现 观察者模式

于 2012-02-26T14:55:33.507 回答
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是 a 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]);
    }
}

更多信息: https ://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Notifications/Introduction/introNotifications.html

https://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/Notification.html

https://developer.apple.com/library/mac/#documentation/Darwin/Conceptual/MacOSXNotifcationOv/Introduction/Introduction.html

于 2012-02-26T15:12:52.180 回答
2

正如 ennukiller 所建议的,在 obj-c 中实现观察者模式的一种简单方法是使用NSNotificationCenterclass. 有关详细信息,请参阅其类参考

编辑

另一种方法是使用 KVO(键值观察)。这更复杂,但相对于第一个具有更好的性能。有关简单说明,请参阅Jeff Lamarche 博客KVO 参考

希望能帮助到你。

于 2012-02-26T15:00:07.080 回答