通过Objective-C中的NSNotificationCenter发送和接收消息?

602 objective-c nsnotificationcenter ios

我试图通过NSNotificationCenterObjective-C 发送和接收消息.但是,我还没有找到任何关于如何做到这一点的例子.你如何通过发送和接收消息NSNotificationCenter

dre*_*lax 1007

@implementation TestClass

- (void) dealloc
{
    // If you don't remove yourself as an observer, the Notification Center
    // will continue to try and send notification objects to the deallocated
    // object.
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

- (id) init
{
    self = [super init];
    if (!self) return nil;

    // Add this instance of TestClass as an observer of the TestNotification.
    // We tell the notification center to inform us of "TestNotification"
    // notifications using the receiveTestNotification: selector. By
    // specifying object:nil, we tell the notification center that we are not
    // interested in who posted the notification. If you provided an actual
    // object rather than nil, the notification center will only notify you
    // when the notification was posted by that particular object.

    [[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(receiveTestNotification:) 
        name:@"TestNotification"
        object:nil];

    return self;
}

- (void) receiveTestNotification:(NSNotification *) notification
{
    // [notification name] should always be @"TestNotification"
    // unless you use this method for observation of other notifications
    // as well.

    if ([[notification name] isEqualToString:@"TestNotification"])
        NSLog (@"Successfully received the test notification!");
}

@end
Run Code Online (Sandbox Code Playgroud)

......在另一个班级的其他地方......

- (void) someMethod
{

    // All instances of TestClass will be notified
    [[NSNotificationCenter defaultCenter] 
        postNotificationName:@"TestNotification" 
        object:self];

}
Run Code Online (Sandbox Code Playgroud)

  • @Fulvio:这取决于,如果您正在接收或发布可能影响应用程序所有部分的通知,请将其放入AppDelegate.如果您正在接收/发布仅影响单个班级的通知,请将其放入该班级. (14认同)
  • 值得一提的是,在ARC下不允许在dealloc方法中使用`[super dealloc]`调用; 其余的都很好. (7认同)
  • 只是想知道[NSNotificationCenter defaultCenter]的位置.最好将它放在AppDelegate中吗? (2认同)

Mic*_*son 223

扩展dreamlax的示例 ...如果要与通知一起发送数据

在发布代码中:

NSDictionary *userInfo = 
[NSDictionary dictionaryWithObject:myObject forKey:@"someKey"];
[[NSNotificationCenter defaultCenter] postNotificationName: 
                       @"TestNotification" object:nil userInfo:userInfo];
Run Code Online (Sandbox Code Playgroud)

在观察代码时:

- (void) receiveTestNotification:(NSNotification *) notification {

    NSDictionary *userInfo = notification.userInfo;
    MyObject *myObject = [userInfo objectForKey:@"someKey"];
}
Run Code Online (Sandbox Code Playgroud)


j7n*_*n7k 48

这个帮助了我:

// Add an observer that will respond to loginComplete
[[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(showMainMenu:) 
                                                 name:@"loginComplete" object:nil];


// Post a notification to loginComplete
[[NSNotificationCenter defaultCenter] postNotificationName:@"loginComplete" object:nil];


// the function specified in the same class where we defined the addObserver
- (void)showMainMenu:(NSNotification *)note {
    NSLog(@"Received Notification - Someone seems to have logged in"); 
}
Run Code Online (Sandbox Code Playgroud)

资料来源:http: //www.smipple.net/snippet/Sounden/Simple%20NSNotificationCenter%20example


Xav*_*Gil 48

还有可能使用块:

NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter] 
     addObserverForName:@"notificationName" 
     object:nil
     queue:mainQueue
     usingBlock:^(NSNotification *notification)
     {
          NSLog(@"Notification received!");
          NSDictionary *userInfo = notification.userInfo;

          // ...
     }];
Run Code Online (Sandbox Code Playgroud)

Apple的文档

  • 我也这么认为,但事实证明这太好了.在这种情况下,您必须保留addObserver返回的观察者,然后删​​除它,这使得它像创建新方法一样复杂,如果不是这样的话.更多信息:http://toastmo.com/blog/2012/12/04/be-careful-using-nsnotificationcenter/ (5认同)

eir*_*ran 41

如果您使用NSNotificationCenter更新视图,请不要忘记通过调用dispatch_async以下命令从主线程发送它:

dispatch_async(dispatch_get_main_queue(),^{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"my_notification" object:nil];
});
Run Code Online (Sandbox Code Playgroud)


Man*_*h M 8

新手选择答案的 SWIFT 5.1

class TestClass {
    deinit {
        // If you don't remove yourself as an observer, the Notification Center
        // will continue to try and send notification objects to the deallocated
        // object.
        NotificationCenter.default.removeObserver(self)
    }

    init() {
        super.init()

        // Add this instance of TestClass as an observer of the TestNotification.
        // We tell the notification center to inform us of "TestNotification"
        // notifications using the receiveTestNotification: selector. By
        // specifying object:nil, we tell the notification center that we are not
        // interested in who posted the notification. If you provided an actual
        // object rather than nil, the notification center will only notify you
        // when the notification was posted by that particular object.

        NotificationCenter.default.addObserver(self, selector: #selector(receiveTest(_:)), name: NSNotification.Name("TestNotification"), object: nil)
    }

    @objc func receiveTest(_ notification: Notification?) {
        // [notification name] should always be @"TestNotification"
        // unless you use this method for observation of other notifications
        // as well.

        if notification?.name.isEqual(toString: "TestNotification") != nil {
            print("Successfully received the test notification!")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

......在另一个班级的其他地方......

 func someMethod(){
        // All instances of TestClass will be notified
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "TestNotification"), object: self)
 }
Run Code Online (Sandbox Code Playgroud)