标签:ons 通知 add 比较 obj post 观察 oda 简介
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context;
- (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary*)change context:(nullable void *)context;
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath;
NSKeyValueObservingOptionNew 把更改之后的值提供给处理方法。
NSKeyValueObservingOptionOld 把更改之前的值提供给处理方法。
NSKeyValueObservingOptionInitial 把初始化的值提供给处理方法,一旦注册,立马就会调用一次。通常它会带有新值,而不会带有旧值。
NSKeyValueObservingOptionPrior 分2次调用。在值改变之前和值改变之后。
keyPath: 对应forKeyPath
object:? 被观察的对象
change:? 对应options里的NSKeyValueObservingOptionNew、NSKeyValueObservingOptionOld等
context: 对应context
@property (nonatomic, strong) Student? *student;
- (void)viewDidLoad {
? [super viewDidLoad];
? _student = [[Student alloc] init];
? _student.age = 10;
? [_student addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];
? [self requestHTTP];
}
- (void)requestHTTP {
? ? AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
? ? [manager POST:urlString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id? _Nullable responseObject) {
? ? ? ?NSInteger age = [(NSDictionary *)responseObject[@"age"] integerValue];
? ? ? ?_student.age = age;
? ?} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
? ?}];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context{
? if ([keyPath isEqualToString:@"age"] && object == _student){
? ? NSLog(@"当前年龄是: %ld",_student.age);
}
}
- (void)dealloc{
? [_student removeObserver:self forKeyPath:@"age"];
}
标签:ons 通知 add 比较 obj post 观察 oda 简介
原文地址:https://www.cnblogs.com/CH520/p/9562671.html