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

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

-(void)ReceiveEvent
{
postNotificationName: --- object:---
}
@end

与另一个类相同,ClassB 也应该能够发送和接收事件。如何做呢?

有帮助吗?

解决方案

理想情况下,对象在初始化后就会开始观察有趣的事件。因此,它将在其初始化代码中向通知中心注册所有感兴趣的事件。 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

B 类也一样。

编辑1:

您可能使问题过于复杂化。NSNotificationCenter 充当所有事件发送到的代理,并决定将事件转发给谁。这就像 观察者模式 但对象并不直接观察或通知彼此,而是通过中央代理(本例中为 NSNotificationCenter)。这样,您就不需要直接连接两个可能相互交互的类 #include.

在设计你的类时,不要担心一个对象如何得到通知,或者如何通知其他感兴趣的对象,只需要一个对象在某些事件发生时需要得到通知,或者它需要在事件发生时通知 NSNotficationCenter它们发生了。

简而言之,找出一个对象应该知道的所有事件,并将这些事件注册到 this 中 init() 方法,并在 dealloc() 方法。

你可能会发现这个 基础教程 有帮助。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top