【问题标题】:passing data using Notification,iphone [duplicate]使用通知传递数据,iphone [重复]
【发布时间】:2012-04-23 20:26:55
【问题描述】:

可能重复:
pass NSString variable to other class with NSNotification

我的问题是:我们是否可以使用 Iphone 通知类中的 postNotificationName 和 addObserver 将数据从一个视图控制器传递到另一个视图控制器

【问题讨论】:

    标签: iphone ios


    【解决方案1】:

    您可以在 API 调用的 userDictionary 元素中传递数据

    NSDictionary *aDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
                              anObject, @"objectName", 
                              anotherObject, @"objectId",
                              nil] autorelease];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"AnythingAtAll" object:nil userInfo:aDictionary];
    

    您可以从您观察到的入站通知中检索字典。在发布通知之前添加观察者。

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(anyAction:) name:@"AnythingAtAll" object:nil];
    

    这可能在您的 init 方法或 viewDidLoad 方法中

    -(void)anyAction:(NSNotification *)anote
    {
    NSDictionary *dict = [anote userInfo];
    AnyClass *objectIWantToTransfer = [dict objectForKey:@"objectName"];
    }
    

    请注意,您应该在 dealloc 方法中将您的对象作为观察者移除。

    [[NSNotificationCenter defaultCenter] removeObserver:self]
    

    【讨论】:

    • 感谢您的帮助。但是,您如何才能先 addObserver 然后再执行 postNotificationName。在here,我和你做同样的事情,但 selector 毕竟没有被调用。
    • 是的,以澄清您需要在发布通知之前添加观察者。通常会在 init 或 viewdidload 方法中。
    • 我需要更多示例。请提供更多关于 postnotifications 的示例链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    相关资源
    最近更新 更多