iOS - 使用 KVO 跟踪对象实例
iOS - Keeping Track Of An Object Instance Using KVO
是否可以跟踪对象的实例以检查它是否已分配和初始化或设置为 nil?
我在 .h 文件中声明了对象,也在 .m 文件中尝试过。
@interface ViewController : UIViewController
@property (nonatomic, strong) TestObject *testObj;
@end
然后我试了这个但是没有用。
- (void)viewDidLoad
{
[super viewDidLoad];
[self addObserver:self forKeyPath:@"testObj" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
_testObj = [[TestObject alloc] init];
}
这样试试:
- (void)viewDidLoad
{
[super viewDidLoad];
[self addObserver:self forKeyPath:NSStringFromSelector(@selector(testObj)) options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
_testObj = [[TestObject alloc] init];
}
然后这样观察:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
if ([keyPath isEqualToString:NSStringFromSelector(@selector(testObj))]) {
//PERFORM YOUR OPERATIONS
}
}
使用 属性 setter 设法让它工作。
所以,而不是:
_testObj = [[TestObject alloc] init];
我是这样做的:
self.testObj = [[TestObject alloc] init];
是否可以跟踪对象的实例以检查它是否已分配和初始化或设置为 nil?
我在 .h 文件中声明了对象,也在 .m 文件中尝试过。
@interface ViewController : UIViewController
@property (nonatomic, strong) TestObject *testObj;
@end
然后我试了这个但是没有用。
- (void)viewDidLoad
{
[super viewDidLoad];
[self addObserver:self forKeyPath:@"testObj" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
_testObj = [[TestObject alloc] init];
}
这样试试:
- (void)viewDidLoad
{
[super viewDidLoad];
[self addObserver:self forKeyPath:NSStringFromSelector(@selector(testObj)) options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
_testObj = [[TestObject alloc] init];
}
然后这样观察:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
if ([keyPath isEqualToString:NSStringFromSelector(@selector(testObj))]) {
//PERFORM YOUR OPERATIONS
}
}
使用 属性 setter 设法让它工作。
所以,而不是:
_testObj = [[TestObject alloc] init];
我是这样做的:
self.testObj = [[TestObject alloc] init];