胖鸭 2010-02-03 11:47
浏览 210
已采纳

通过位于 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条回答 默认 最新

  • 狐狸.fox 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条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line