Iphone 目标-C-NSNotificationCenter在哪里?

Iphone 目标-C-NSNotificationCenter在哪里?,iphone,objective-c,Iphone,Objective C,我有一个NSNotificationCenter选择器 放在哪里?在控制器的代理中(如果是,则在哪里?) 把方法也放在哪里 我需要解除NSNotificationCenter的锁定吗 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceNotificationReceived:) name:UIApplicationDidBecomeActiveNotification object:ni

我有一个NSNotificationCenter选择器

放在哪里?在控制器的代理中(如果是,则在哪里?)

把方法也放在哪里

我需要解除NSNotificationCenter的锁定吗

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceNotificationReceived:) name:UIApplicationDidBecomeActiveNotification object:nil];



- (void)deviceNotificationReceived:(NSNotification *)notification
{
    [self.soundMgr endInterruption];
}

deviceNotificationReceived:
方法必须是
addObserver:
参数的实例方法。在本例中,它是
self
,因此您的方法应该放在同一个类中

您不应该释放NotificationCenter,因为您没有创建或保留它

你的问题有点难理解,这就是你要问的吗

嗨,我有一个NSNotificationCenter选择器

好的,你的意思是在NSNotificationCenter中有一个方法选择器

在Objective-C中,“选择器”有两个 意义。可供参考 只需在 它在源代码消息中用于 物体。不过,它也提到了 替换的唯一标识符 源代码被删除时的名称 编译。

因此,您已经创建了一个引用方法的选择器

放在哪里

这是一个变量,您可以将其存储在任何适合您设计的地方

在代表中

见上文

(如果是,那么在哪里?)

这是一个变量,取决于您的使用情况

在控制器中

你们有控制器吗?取决于你的设计

把方法也放在哪里

哪种方法

我需要解除NSNotificationCenter的锁定吗

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceNotificationReceived:) name:UIApplicationDidBecomeActiveNotification object:nil];



- (void)deviceNotificationReceived:(NSNotification *)notification
{
    [self.soundMgr endInterruption];
}

否,
[NSNotificationCenter defaultCenter]
返回对通知中心的引用,您不会解除锁定它。

因为您订阅的是
UIApplicationIDBecomeActivityNotification
通知,放置通知的最合理位置是应用程序代理的
ApplicationDidFinishLaunching
方法

这是您的代码被调用的第一个点,因此您不能提前设置它。

将其放置在何处


这取决于您何时需要注册通知。一种方法是在类的“init”方法中添加观察者,并在类的“dealoc”方法中删除通知。

ok。因此,如果我需要,我的ViewController将收到该通知,例如,在输入并放弃呼叫后,应用程序返回,应用程序需要调用此方法,我将把NSNotificationCenter放在哪里调用该方法?如果需要,您可能应该将调用放在ViewController中的
initWithNibName:bundle:
中。因为这是一个iPhone应用程序,我认为viewDidLoad:可能是一个更好的位置,然后在viewDidUnload:中注销。通常,您只希望视图响应UIApplicationIDBecMeactiveNotification,前提是该视图在创建时是活动视图interruption@bodnarbm如果它是根视图控制器,则可能更好;如果视图是延迟加载的,则可能会导致一些问题。