使用Notification,iphone传递数据

时间:2012-04-23 20:26:55

标签: iphone ios

  

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

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

1 个答案:

答案 0 :(得分:18)

您可以在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]