℡Wang Yan 2010-02-03 11:47 采纳率: 100%
浏览 279
已采纳

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

  • 10.24 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 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等