我在学习关于NSNotificationCenter的知识。以下是我的代码
Observer.m
//note init method is not complete here
-(id) init
{
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(reciveTestNotification:)
name:@"TestNotification" object:nil];
}
-(void)reciveTestNotification:(NSNotification *)notification
{
if([[notification name] isEqualToString:@"TestNotification"])
{
NSLog(@"Succesfuly received the test notification");
}
}Osender.m
-(void)reciveTestNotification:(NSNotification *)notification
{
if([[notification name] isEqualToString:@"TestNotification"])
{
NSLog(@"Succesfuly received the test notification");
}
}我想我理解NSNotification是如何工作的,但是如何通过NSNotification传递ivar呢?
假设Osender.h有这样的代码
Osender.h
@interface Osender : NSObject
{
IBOutlet UITextField *txt;
}
@property (nonatopic, copy) IBOutlet (UITextField *) *txt当用户在txt上输入或更改内容时,如何通知reciveTestNotification并将数据传递给它?
发布于 2012-01-30 19:51:16
NSNotification类有一个属性,用于存储您可能想要随通知一起发送的附加数据,即userInfo。
你可以这样发布它:
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:txt forKey:@"textField"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:self userInfo:userInfo]然后像这样得到它:
- (void)reciveTestNotification:(NSNotification *)notification
{
UITextField *textField = [notification.userInfo objectForKey:@"textField"];
}现在textField有了对您的UITextField的引用。
发布于 2012-01-30 19:41:25
您可以将自定义数据放入通知的userInfo中,它是一个NSDictionary实例。您需要确保通知的发布者在字典中创建的密钥与通知使用者期望的密钥相同。
发布于 2012-01-30 19:50:47
使用NSNotificationCenter的这种方法
- (void)postNotificationName:(NSString *)notificationName object:(id)notificationSender userInfo:(NSDictionary *)userInfo并将userInfo设置为包含要传递的数据的NSDictionary:
NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:@"object", @"key", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:nil userInfo:infoDict];https://stackoverflow.com/questions/9063217
复制相似问题