学习中ing...

属性传值、block传值、delegate传值、KVO监听属性变

2018-01-22  本文已影响0人  那片阳光已醉

忙里得闲,总算有时间来思考一下了,作为一枚资深码农最近真的很急躁呢。跟一个朋友聊天之后感觉自己这段时间就是一个真真的搬砖人啊,只是停留在表面UI方面;
今天问了同事一个问题之后瞬间泪崩了啊,如何监听到同一个.m文件属性的变化😩。
说到这里了我就来写下几种传值的方式

传送门

    [super viewDidLoad];
    self.person = [[Person alloc]init];
    //观察person对象的 name属性值的改变
    [self.person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)dealloc
{
    //移除kvo
    [self.person removeObserver:self forKeyPath:NSStringFromSelector(@selector(name))];
}

#pragma mark  ************** 监听属性变化 ************** shutong **
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"name"]) {
        self.KVOContent.text = [NSString stringWithFormat:@"%@%@",self.person.name ? self.person.name : @"",self.person.sex ? self.person.sex : @""];
        self.KVOContent.backgroundColor = [UIColor blueColor];
    }
}
#pragma mark  ************** touch event ************** shutong **

- (IBAction)changeAction:(id)sender {
    self.currentProperty = @"属性传值";
    self.person.name = @"kvo传值";
    self.person.sex = @"未知";
    
}

- (IBAction)skipAction:(id)sender {
    ChangeViewController *changeVC = [[ChangeViewController alloc]init];
    __weak typeof(self)weakSelf = self;
    changeVC.changeValue = ^(NSString *value) {
        weakSelf.blockContent.text = value ? value : @"";
        weakSelf.blockContent.backgroundColor = [UIColor greenColor];
    };
    changeVC.delegate = self;
    [self presentViewController:changeVC animated:YES completion:^{
        
    }];
}
- (void)testDelegateChangeValue:(NSString *)value
{
    self.delegateContent.text = value ? value : @"";
    self.delegateContent.backgroundColor = [UIColor yellowColor];
}
#pragma mark  ************** setter / getter ************** shutong **

- (void)setCurrentProperty:(NSString *)currentProperty
{
    _currentProperty = currentProperty;
    self.PropertyContent.text = currentProperty;
    self.PropertyContent.backgroundColor = [UIColor orangeColor];
} ```

上一篇 下一篇

猜你喜欢

热点阅读