?yb? 2010-02-03 11:47 采纳率: 100%
浏览 252
已采纳

通过位于 Objective-C 的 NSNotificationCenter 发送和接收消息? [打烊]

I am attempting to send and receive messages through NSNotificationCenter in Objective-C. However, I haven't been able to find any examples on how to do this. How do you send and receive messages through NSNotificationCenter?

转载于:https://stackoverflow.com/questions/2191594/send-and-receive-messages-through-nsnotificationcenter-in-objective-c

  • 写回答

5条回答 默认 最新

  • python小菜 2010-02-03 12:25
    关注
    @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
    

    ... somewhere else in another class ...

    - (void) someMethod
    {
    
        // All instances of TestClass will be notified
        [[NSNotificationCenter defaultCenter] 
            postNotificationName:@"TestNotification" 
            object:self];
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!