在項目開發中定義了一個單例對象RHUserData的對象,RHOLUserInfo類是單例對象的一個property屬性,RHOLUserInfo裏面有個userId的屬性,在其餘類裏面進行設置KVO,安全
在A類裏面設置監聽:app
[[RHOLUserData shareInstance].userInfo addObserver:self forKeyPath:@"userId" options:NSKeyValueObservingOptionNew context:nil];
在B類裏面進行對RHOLUserInfo賦值操做:spa
[RHOLUserData shareInstance].userInfo = newUserInfo;
這個操做在iOS 11以上是不會有異常的,可是在iOS 11一下的版本就會報錯,致使crash的問題:3d
異常日誌輸出:日誌
[17369:6096714] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: 'An instance 0x1700cfb20 of class RHOLUserInfo was deallocated while key value observers were still registered with it.
Current observation info: <NSKeyValueObservationInfo 0x17003db80> ( <NSKeyValueObservance 0x17024ad10: Observer: 0x17404fdb0, Key path: userId, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x17024ad40> )' *** First throw call stack: (0x18b8ba1c0 0x18a2f455c 0x18b8ba108 0x18c30ad64 0x1043ec5b8 0x1000d3384 0x104386da4 0x1043861a0 0x10379ec9c 0x1037c0ff4 0x1055f125c
0x1055f121c 0x1055f5fb0 0x18b867f2c 0x18b865b18 0x18b794048 0x18d21a198 0x1917802fc 0x19177b034 0x1001270c0 0x18a7785b8) libc++abi.dylib: terminating with uncaught exception of type NSException
在錯誤日誌裏面也提醒的很清楚,「RHOLUserInfo was deallocated while key value observers were still registered with it」,意思是說單例裏面的RHOLUserInfo屬性舊內存已經被釋放了可是KVO仍是繼續監聽,code
解決方案:server
最簡單的解決方案是RHOLUserInfo裏面的property屬性相對就少的狀況下(3個如下),能夠進行手動賦值:對象
[RHOLUserData shareInstance].userInfo.userId = newUserInfo.userId;
複雜的對象屬性特別多的時候,這樣寫就太糟糕了,推薦使用YYKit裏面的YYModel進行屬性賦值操做安全方便:)blog
[[RHOLUserData shareInstance].userInfo modelSetWithDictionary:[newuserInfo toDictionary]];
注意:以上對象都是繼承了JSONModel對象才能進行對象轉換字典的操做。繼承