码迷,mamicode.com
首页 > 其他好文 > 详细

KVC(2)

时间:2015-06-30 22:04:16      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:kvo

@interface Walker : NSObject
{
    NSInteger _age;
    NSString *_name;
}
@property (nonatomic) NSInteger age;
@property (nonatomic, retain) NSString *name;
- (id)initWithName:(NSString *)name age:(NSInteger)age;

``

import “Walker.h”

@implementation Walker

  • (id)initWithName:(NSString *)name age:(NSInteger)age
    {
    if (self = [super init]) {
    _name = name;
    _age = age;
    }
    return self;
    }
    @end

import

  • (void)viewDidLoad {
    [super viewDidLoad];

    _walker = [[Walker alloc] initWithName:@”LJF” age:25];
    NSLog(@”%ld”, (long)_walker.age);
    /* 关键步骤 */
    [_walker addObserver:self
    forKeyPath:@”age”
    options:NSKeyValueObservingOptionNew
    context:nil];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
     [btn setFrame:CGRectMake(120, 200, 100, 35)];
     [btn setBackgroundColor:[UIColor lightGrayColor]];
     [btn setTitle:@"增加5岁" forState:UIControlStateNormal];
     [btn addTarget:self
                     action:@selector(buttonPressed)
           forControlEvents:UIControlEventTouchUpInside];
     [self.view addSubview:btn];
    
     _ageLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 150, 200, 35)];
     _ageLabel.text = [NSString stringWithFormat:@"%@现在的年龄是: %ld", _walker.name, (long)_walker.age];
     _ageLabel.backgroundColor = [UIColor clearColor];
     [self.view addSubview:_ageLabel];
    

    }

  • (void)buttonPressed
    {
    _walker.age += 5;

    }

    /* KVO function, 只要object的keyPath属性发生变化,就会调用此函数*/

    • (void)observeValueForKeyPath:(NSString )keyPath ofObject:(id)object change:(NSDictionary )change context:(void *)context
      {
      NSLog(@”keyPath = %@ \nobject =%@ \nchange = %@ \n”, keyPath,object,change);
      if ([keyPath isEqualToString:@”age”] && object == _walker) {
      _ageLabel.text = [NSString stringWithFormat:@”%@现在的年龄是: %ld”, _walker.name, (long)_walker.age];
      }
      }
      如下图:
      “`
      技术分享
      技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

KVC(2)

标签:kvo

原文地址:http://blog.csdn.net/tubiebutu/article/details/46699371

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!