在目标c中注册课程 [英] register a class in objective c
问题描述
让我说我有classA
这是一类音频,它对音频输入进行多次采样.
每次class A
获得新数据(在一秒钟内可能发生很多次),他都需要通知另一个类,即classB
.
lets say i have classA
which is a class of audio,that sample the audio input many times.
each time class A
get a new data (can happen many times in second), he needs to inform another class, which is classB
.
现在,我可以在classA
中创建class B
的实例,并在收到新数据时调用B,但这不是模块化软件.
Now, i could just make an instance of class B
in classA
and call B when there is a new data arrived, but this is not a modular software.
我希望classA
在外面是盲目的",只是将他添加到每个项目中,并希望有另一个classB
可以使他register
某种方式,所以当A有新内容时,B会知道的((没有A呼叫B!)
i want classA
to be "blind" to the outside, and just to add him to every project, and to have another classB
that will register
him some how, so when A has something new, B will know about it,(without A calling B ! )
它在目标c中是如何正确完成的?
how its done right in objective c ?
非常感谢.
推荐答案
您可以在ClassA
中发布一个通知,并在其他类中对该通知进行 register (即ClassB
).
You can post a notification in ClassA
, and register for that notification in other classes (namely ClassB
).
这是您可以执行的操作:
This is how you can do it:
(在ClassA
中):
[[NSNotificationCenter defaultCenter]
postNotificationName:@"noteName" object:self];
(在ClassB
中):
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(doSomething:)
name:@"noteName" object:nil];
每当ClassA
实例发布新通知时,都会(立即)通知其他已向该通知注册的实例.在这种情况下,ClassB
将执行doSomething:(NSNotification *)note
.
Whenever an instance of ClassA
posts a new notification, other instances that have registered to that notification will be informed (instantaneously). In this case, ClassB
will perform doSomething:(NSNotification *)note
.
您可以将该通知发布到您的设置方法(setVar:(NSString*)newVar
).
You can post that notification your setter method (setVar:(NSString*)newVar
).
如果您想传递一些东西,请使用postNotificationName:object:userInfo:
变体. userInfo
是NSDictionary
,您可以在其中传递任何内容.例如:
If you want to pass something along, use the postNotificationName:object:userInfo:
variant. userInfo
is a NSDictionary
and you can pass anything you want in it. for example:
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]);
}
}
More info: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Notifications/Introduction/introNotifications.html
这篇关于在目标c中注册课程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!