【问题标题】:What does the 'object' argument do in `postNotificationName:object:`?`postNotificationName:object:` 中的 'object' 参数有什么作用?
【发布时间】:2013-10-11 19:03:24
【问题描述】:
- (void)postNotificationName:(NSString *)notificationName 
                      object:(id)notificationSender

谁能帮我理解上面方法中的object参数?

我用过

[[NSNotificationCenter defaultCenter] postNotificationName:@"Downloadfinished"
                                                    object:self]; 

[[NSNotificationCenter defaultCenter] postNotificationName:@"Downloadfinished"
                                                    object:nil];

他们在我的情况下工作。但我想了解这个论点的作用以及我应该传递什么。

【问题讨论】:

标签: ios objective-c nsnotificationcenter


【解决方案1】:

来自文档:

notificationSender 
The object posting the notification.

就是这样,您可能需要它,也可能不需要。如果你在收到通知时没有使用它,它是否为 nil 无关紧要。

查看文档:

NSNotificationCenter

【讨论】:

  • 我会说,当您不使用此参数时发送self 可能会使试图理解代码的人感到困惑。如果消息只是发生某事的信息并且您不需要上下文 - 发送nil。目的明确。
【解决方案2】:

NSNotification具有以下三个属性:

  1. name - 通知的唯一标识符。
  2. object - 一个id 参数,可以传递给接收方,如果需要,可以在接收端用于任何目的
  3. userInfo - NSDictionary 对象:如果您想传递多个对象,请使用键/值对创建一个 NSDictionary,然后继续传递。

如果您不想将任何内容传递给接收者,请将nil 传递给object

【讨论】:

    【解决方案3】:

    案例:自我

    当您将对象写为 Self 或任何其他对象时,这意味着 通知将与对象一起触发意味着将对象作为 通知参数。

    你会得到如下的对象:

    示例

    [[NSNotificationCenter defaultCenter] postNotificationName:kProductsLoadedNotification object:self];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(productsRequestCompleted:)
                                                         name:kProductsLoadedNotification
                                                       object:self];
    - (void)productsRequestCompleted:(NSNotification *)notification
    {
    NSLog("%@",[notification object]); //You will get the Parameter
    }
    

    案例:无

    当您将对象写为 nil 时,这意味着 通知将在没有对象的情况下触发意味着没有将对象作为 通知参数。

    【讨论】:

    • 这对您有帮助吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 2020-01-21
    • 2015-09-07
    • 2017-03-12
    • 1970-01-01
    相关资源
    最近更新 更多