KVO key -- value -- observer 键值对观察者
它的主要作用就是用来监听属性里的内容发生的变化
监听的对象必须是观察者属性, 参数二:要监听的属性必须和keyPath保持一致,否则不会触发方法, 参数三:触发的条件,就是旧值和新值变化的时候(绘制走势图,形势图)
// self.stu = [[Student alloc] init];
// // 观察者就是self试图控制器
// [self.stu addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew |NSKeyValueObservingOptionOld context:@"hello"];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
NSLog(@"keyPath = %@", keyPath);
NSLog(@"change = %@", change);
NSLog(@"context = %@", context);
}
keyPath=name change{ kind = 1 new = jack old = <null>} context = hello
交叉引用的问题,用@class文件名;在.m文件引头文件(从后往前属性传值,可能会引起交叉引用的问题)
通知中心(从前往后传值的第四种方式)
1.使用一:传值[NSNotificationCenter defaultCenter],通过userInfo传值
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:@"chengjin" object:nil];
<span style="font-weight: normal;"><span style="font-size:14px;">- (void)change:(NSNotification *)notification{
// 通过userInfo传值
NSLog(@"%@", notification.userInfo);
}</span></span><span style="font-size:18px;">
</span>
<span style="font-weight: normal;"><span style="font-size:14px;">- (void)change:(NSNotification *)notification{
// 通过userInfo传值
NSLog(@"%@", notification.userInfo);
}</span></span><span style="font-size:18px;">
</span>
2.使用二:监听文本框输入内容(键盘监听的第三种方法) 参数三:必须写 参数四:监听的对象
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValue:) name:UITextFieldTextDidChangeNotification object:self.myTextField];
通过正则表达式,用谓词来判断.当前输入的内容是否符合要求,这个要求可以通过正则表达式来实现
- (void)textFieldValue:(NSNotification *)notification{
// NSLog(@"%@", self.myTextField.text);
// 正则表达式
NSString *str = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
// 通过谓词来判断,当前输入的内容是否符合要求,这个要求就可以通过正则表达式来实现
NSPredicate *cate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
BOOL result = [cate evaluateWithObject:self.myTextField.text];
if (result) {
NSLog(@"电话号码成立");
} else {
NSLog(@"不成立");
}
}