遇到的問題:
今天做MVVM框架的時(shí)候我嘗試寫一個(gè)路由轉(zhuǎn)發(fā)的類寂拆,但是在對(duì)UITabBarViewController的selectedIndex進(jìn)行鍵值觀察的時(shí)候發(fā)現(xiàn)并沒有起作用,用到的具體API芬首。
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context;
- (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary*)change context:(nullable void *)context;未調(diào)用,
具體代碼:
@property (nonatomic, strong) UITabBarController *targetTB;
[self addObserver:self forKeyPath:@"targetTB.selectedIndex" options:NSKeyValueObservingOptionNew context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context
{ ?//break point here }
我不明白系統(tǒng)怎么實(shí)現(xiàn)的漾根,我想嘗試點(diǎn)擊TabBarItem切換selectedindex的時(shí)候是否調(diào)用了selectedIndex的setter方法,我重寫了selectedIndex的setter方法捉偏, 系統(tǒng)并沒有調(diào)用selectedIndex的setter方法 , 而且很奇怪的是在setter方法內(nèi)部取不到_selectedIndex泻红。但是如果我手動(dòng)修改self.targetTB.selectedIndex的值時(shí)夭禽,-observeValueForKeyPath方法被執(zhí)行了。我暫時(shí)在網(wǎng)上沒有找到問題的原因谊路,于是根據(jù)TabBarViewController的其他屬性我迂回實(shí)現(xiàn)了自己想要的效果讹躯。
實(shí)現(xiàn)TabBarViewController點(diǎn)擊切換TabBarItem獲取時(shí)間的具體代碼如下:
@property (nonatomic, strong) UITabBarController *targetTB;
[self addObserver:self forKeyPath:@"targetTB.selectedViewController" options:NSKeyValueObservingOptionNew context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context
{? //write your code here }