【发布时间】:2012-04-23 20:26:55
【问题描述】:
可能重复:
pass NSString variable to other class with NSNotification
我的问题是:我们是否可以使用 Iphone 通知类中的 postNotificationName 和 addObserver 将数据从一个视图控制器传递到另一个视图控制器
【问题讨论】:
可能重复:
pass NSString variable to other class with NSNotification
我的问题是:我们是否可以使用 Iphone 通知类中的 postNotificationName 和 addObserver 将数据从一个视图控制器传递到另一个视图控制器
【问题讨论】:
您可以在 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]
【讨论】: