通过 NSNotificationCenter 传递 ivar
我正在研究 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 上键入或更改某些内容时如何通知 receiveTestNotification 并向其传递数据?
I'm study about NSNotificationCenter. Here is my code
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");
}
}
I think that I undestand how NSNotification works, but how to pass ivar via NSNotification ?
Lets say Osender.h have this code
Osender.h
@interface Osender : NSObject
{
IBOutlet UITextField *txt;
}
@property (nonatopic, copy) IBOutlet (UITextField *) *txt
How to notify reciveTestNotification and pass data to it when user type or change something on txt ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
NSNotification
类有一个属性,用于存储您可能希望与通知一起发送的附加数据,userInfo
。您可以像这样发布它:
并像这样获取它:
现在
textField
具有对您的UITextField
的引用。NSNotification
class has a property for additional data that you might want to send with your notification,userInfo
.You post it like this:
And get it like this:
Now
textField
has the reference to yourUITextField
.您可以将自定义数据放入通知的
userInfo
中,它是一个NSDictionary
实例。您需要确保通知发布者在字典中创建的键与通知使用者期望的键相同。You can put custom data into the notification's
userInfo
, which is aNSDictionary
instance. You need to ensure that the keys created in the dictionary by the notification's poster are the same as the keys expected by the consumers of the notification.使用 NSNotificationCenter 的此方法
并将 userInfo 设置为 NSDictionary 并包含要传递的数据:
use this method of NSNotificationCenter
and set userInfo to an NSDictionary with the data you want to pass: