如何通过Objective-C中的NSNotificationCenter创建一个发送和接收事件的类?

Cat*_*thy 5 objective-c nsnotification nsnotificationcenter

我需要创建两个类,两者都应该能够通过NSNotificationCenter方法发送和接收事件.两者都应该有sendEvent和receiveEvent方法:

      @implementation Class A
-(void)sendEvent
{
    addObserver:---  name:---- object:---
}

-(void)ReceiveEvent
{
postNotificationName: --- object:---
}
@end
Run Code Online (Sandbox Code Playgroud)

与另一个类相同,ClassB也应该能够发送和接收事件.怎么做到呢?

Anu*_*rag 10

理想情况下,一个对象在初始化后就会开始观察有趣的事件.因此,它将在其初始化代码中注册NotificationCenter的所有有趣事件.sendEvent:基本上是该postNotification:方法的包装器.

@implementation A

- (id)init {
    if(self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveEvent:) name:@"SomeEvent" object:nil];
    }
    return self;
}

- (void)sendEvent {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SomeOtherEvent" object:nil];
}

// Called whenever an event named "SomeEvent" is fired, from any object.
- (void)receiveEvent:(NSNotification *)notification {
    // handle event
}

@end
Run Code Online (Sandbox Code Playgroud)

B班也一样

编辑1:

您可能会使问题过于复杂.NSNotificationCenter充当发送所有事件的经纪人,并决定将其转发给谁.它就像Observer模式,但是对象不直接观察或通知对方,而是通过中央代理 - 在这种情况下是NSNotificationCenter.有了它,你不需要直接连接两个可能相互作用的类#include.

在设计类时,不要担心如何通知对象或如何通知其他感兴趣的对象,只需要知道某个对象何时发生通知,或者需要通知NSNotficationCenter其事件的时间.他们发生了.

简而言之,找出对象应该知道的所有事件,并在此init()方法中注册这些事件,并在dealloc()方法中取消注册它们.

您可能会发现此基础教程很有帮助.