【问题标题】:How to use parametrized method with NSNotificationCenter?如何在 NSNotificationCenter 中使用参数化方法?
【发布时间】:2009-06-23 21:18:21
【问题描述】:

我想将 dict 传递给方法 processit。但是一旦我访问字典,我就会得到 EXC__BAD_INSTRUCTION。

NSNotificationCenter *ncObserver = [NSNotificationCenter defaultCenter];
[ncObserver addObserver:self selector:@selector(processit:) name:@"atest"
                 object:nil];

NSDictionary *dict = [[NSDictionary alloc]
                             initWithObjectsAndKeys:@"testing", @"first", nil];
NSString *test = [dict valueForKey:@"first"];
NSNotificationCenter *ncSubject = [NSNotificationCenter defaultCenter];
[ncSubject postNotificationName:@"atest" object:self userInfo:dict];

在接收方方法中:

- (void) processit: (NSDictionary *)name{
    NSString *test = [name valueForKey:@"l"]; //EXC_BAD_INSTRUCTION occurs here
    NSLog(@"output is %@", test);
}

对我做错了什么有什么建议吗?

【问题讨论】:

    标签: objective-c iphone cocoa-touch nsnotifications


    【解决方案1】:

    您将在通知回调中收到一个 NSNotification 对象,而不是一个 NSDictionary。

    试试这个:

    - (void) processit: (NSNotification *)note {
        NSString *test = [[note userInfo] valueForKey:@"l"];
        NSLog(@"output is %@", test);
    }
    

    【讨论】:

      【解决方案2】:

      Amrox 是绝对正确的。

      也可以使用 Object(而不是 userInfo),如下所示:

      - (void) processit: (NSNotification *)note {
      
          NSDictionary *dict = (NSDictionary*)note.object;
      
          NSString *test = [dict valueForKey:@"l"];
          NSLog(@"output is %@", test);
      }
      

      在这种情况下,您的 postNotificationName:object 将如下所示:

      [[NSNotificationCenter defaultCenter] postNotificationName:@"atest" object:dict];
      

      【讨论】:

      • 感谢 Adrian 更新代码。从下一次开始,我也会处理格式。 :)
      【解决方案3】:

      您将在通知回调中收到一个 NSNotification 对象,而不是一个 NSDictionary。

      • (void) processit: (NSNotification *)note {

        NSDictionary dict = (NSDictionary)note.object;

        NSString *test = [dict valueForKey:@"l"];

        NSLog(@"输出为 %@", test); }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-13
        • 1970-01-01
        • 2014-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-06
        相关资源
        最近更新 更多