标签:
#import <Foundation/Foundation.h> @interface MYClass : NSObject @property(assign,nonatomic)int number; @end ----------------------- #import "ViewController.h" #import "MYClass.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UIButton *plusButton; @property (weak, nonatomic) IBOutlet UILabel *showLabel; @property(nonatomic,strong)MYClass *myClass; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; _myClass = [[MYClass alloc] init]; [_myClass addObserver:self forKeyPath:@"number" options:NSKeyValueObservingOptionNew context:nil]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{ if ([keyPath isEqualToString:@"number"]&&object == _myClass) { _showLabel.text = [NSString stringWithFormat:@"%@",[change valueForKey:@"new"]]; } } - (IBAction)makeCountPlus:(id)sender { ++_myClass.number; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; [self removeObserver:self forKeyPath:@"number"]; } @end
转自啊左
标签:
原文地址:http://www.cnblogs.com/garywong1949/p/5487596.html