胖鸭 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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题