使用观察者模式观察变量值修改的位置
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,strong) NSString *testString;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//添加观察者,自己观察自己的 testString
[self addObserver:self forKeyPath:@"testString" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)stringChange1:(UIButton *)sender {
self.testString = @"1";
}
- (IBAction)stringChange2:(UIButton *)sender {
self.testString = @"2";
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
//NSLog(@"%s:%d obj = %@",__func__,__LINE__,object);
NSLog(@"%@",self.testString);//在这一句上打一个断点。
}
@end
在 storyboard 中添加两个按钮,并分别添加方法 stringChange1 和 stringChange2,按下按钮时会断到断点位置,这时看 Xcode——左侧菜单栏——Show the Debug navigator,可以看到是从哪一个方法运行到了这里,从而确定 self.testString 是的值是在哪里被修改。