Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

nsnotification - How to create a class to send and receive events through NSNotificationCenter in Objective-C?

I need to create two classes and both should be able to send and receive the events through the NSNotificationCenter methods.ie Both should have the sendEvent and receiveEvent methods:

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

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

Same as such another class say ClassB should also be able to send and receive the events. How can it be done?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ideally an object would start observing interesting events as soon as its initialized. So it will register all interesting events with the NotificationCenter inside its initialization code. sendEvent: is basically a wrapper around the postNotification: method.

@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

Same for class B.

Edit 1:

You might be over-complicating the problem. A NSNotificationCenter acts as a broker to whom all events are sent and it decides who to forward that to. It's like the Observer pattern but objects don't directly observe or notify each other, but rather through a central broker - the NSNotificationCenter in this case. With that you don't need to directly connect two classes that might be interacting with each other with an #include.

While designing your classes, don't worry about how an object would get notified or how it would notify other interested objects, only that an object needs to get notified about some events when they occur, or it needs to inform NSNotficationCenter of its events when they occur.

So in short, find out all events that an object should know about and register those events in this init() method, and unregister them in the dealloc() method.

You may find this basic tutorial helpful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...