您的位置:首页 > 移动开发 > IOS开发

【深入浅出ios开发】NSNotificationCenter

2014-12-05 10:11 369 查看
我们经常要监听消息,监听消息一般有三种方法:第一种用控件的addtarget来监听消息。第二种通过delegate来监听消息。这里我们讲解用NSNotificationCenter来监听消息。这里有详细的文档:
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/
在一个项目中NSNotificationCenter提供一种机制用来传递消息。NSNotificationCenter对象本质上是一个通知发送表。该对象通过
addObserver:selector:name:object:
addObserverForName:object:queue:usingBlock:
方法来注册通知中心用来接受通知。每次调用该方法都会指定一组通知。因此,对象可以通过多次调用这些方法注册成不同通知组观察员。每一个正在运行的Cocoa程序都有一个默认的通知中心,你通常不必自己创建。一个NSNotificationCenter对象仅仅在一个简单程序中就可以发送通知。如果你希望发送消息到别的进程或者从别的进程接受消息,使用NSDistributedNotificationCenter的实例就行了。①+(NSNotificationCenter
*)defaultCenter用来返回进程默认的NSNotificationCenter②- (void)addObserver:(id)
notificationObserver
//观察者,即在什么地方接收通知;
selector:(SEL)
notificationSelector
//收到通知后调用何种方法;
name:(NSString *)
notificationName//通知的名字,也是通知的唯一标示
object:(id)
notificationSender//通知发送者
监听TextField,如果里面有数据则按钮可以使用,否则不行。
①首先创建相应的变量:2个UITextField,一个UIButton,然后连线。
@property (weak, nonatomic) IBOutlet UITextField *textfieldName;
@property (weak, nonatomic) IBOutlet UITextField *textfieldPassword;
@property (weak, nonatomic) IBOutlet UIButton *landButton;

②在viewDidLoad中设置相应的NSNotificationCenter.
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(buttonCanInput) name:UITextFieldTextDidChangeNotification object:self.textfieldName];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(buttonCanInput) name:UITextFieldTextDidChangeNotification object:self.textfieldPassword];
// Do any additional setup after loading the view.
}
③buttonCanInput方法的设置:
-(void)buttonCanInput
{
self.landButton.enabled = (self.textfieldName.text.length && self.textfieldPassword.text.length);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: