【深入浅出ios开发】NSNotificationCenter

我们经常要监听消息,监听消息一般有三种方法:第一种用控件的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);
}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值