我正在研究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并将数据传递给它?
答案 0 :(得分:2)
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
。
答案 1 :(得分:1)
您可以将自定义数据放入通知userInfo
,这是NSDictionary
个实例。您需要确保通知海报在字典中创建的密钥与通知消费者期望的密钥相同。
答案 2 :(得分:0)
使用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];