在目标c中注册一个班级

时间:2012-02-26 14:52:39

标签: objective-c observer-pattern decoupling

假设我有classA这是一类音频,它会多次采样音频输入。 每次class A获取新数据(可能在第二次发生多次)时,他需要通知另一个班级,classB

现在,我可以在class B中创建classA的实例,并在有新数据到达时调用B,但这不是模块化软件。

我希望classA对外界“盲目”,只是为了将他添加到每个项目中,并让另一个classBregister他一些如何,所以当A有新的东西,B会知道它,(没有A叫B!)

它如何在目标c中完成?

非常感谢。

3 个答案:

答案 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:变体。 userInfoNSDictionary,您可以传递任何内容。例如:

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

答案 2 :(得分:2)

正如ennuikiller所建议的,在obj-c中实现观察者模式的一种简单方法是使用NSNotificationCenter类。详情请见see its class reference

修改

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

希望它有所帮助。