簡體   English   中英

當使用KVO和delaySelector觀察NSUserDefaults時,iOS exc_bad_access

[英]iOS exc_bad_access when observing NSUserDefaults with KVO and delayedSelector

我遇到了一個奇怪的錯誤,想檢查我是否使用我的Key值來正確觀察NSUserDefaults的更改。

我已經在我的應用程序中的兩個地方使用了此代碼,沒有問題,然后添加了第三個控制器,用於觀察“ goldCount”和“ energyCount”的值。 現在,當我設置初始值時,應用程序因exc_bad_access而崩潰。 我在使用performSelectorAfterDelay其父視圖出現2秒后,將該控制器添加到視圖中。

在顯示游戲屏幕之前,我設置了以下屬性:

//crash on this line 
[[NSUserDefaults standardUserDefaults] setInteger:200 forKey: goldCount]; 

[[NSUserDefaults standardUserDefaults] setInteger:150 forKey: energyCount];

在3個不同的視圖控制器中,我在viewDidLoad中具有以下代碼:

NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults addObserver:self
           forKeyPath:@"goldCount"
              options:NSKeyValueObservingOptionNew
              context:NULL];

[defaults addObserver:self
           forKeyPath:@"energyCount"
              options:NSKeyValueObservingOptionNew
              context:NULL];

self.goldLabel.text = [NSString stringWithFormat:@"%i",[[GameDataManager sharedInstance] currentGoldCount]];
self.energyLabel.text = [NSString stringWithFormat:@"%i",[[GameDataManager sharedInstance] currentEnergyCount]];

該類如何更新其標簽:

// KVO handler
-(void)observeValueForKeyPath:(NSString *)aKeyPath ofObject:(id)anObject
                       change:(NSDictionary *)aChange context:(void *)aContext
{

    //aKeyPath gives us the name of a user default that has changed
    if([aKeyPath isEqualToString:@"goldCount"])
    {
        //we are interested in the new value
        self.goldLabel.text = [NSString stringWithFormat:@"%i",[[aChange objectForKey:@"new"] intValue]];
    }else if([aKeyPath isEqualToString:@"energyCount"])
    {
        self.energyLabel.text = [NSString stringWithFormat:@"%i",[[aChange objectForKey:@"new"] intValue]];
    }

}

向[[NSUserDefaults standardUserDefaults]同步]添加呼叫后; 我第二次收到此異常:

由於未捕獲的異常'NSInternalInconsistencyException'而終止應用程序,原因:'():收到但未處理-observeValueForKeyPath:ofObject:change:context:消息。 關鍵路徑:goldCount觀察到的對象:更改:{kind = 1; 新= 205; 上下文:0x0'

未記錄NSUserDefaults是否兼容KVO,因此無法通過其鍵遵守默認值。 這可能是導致崩潰的原因,但是如果沒有堆棧跟蹤就無法分辨。

您可以注冊一個通知,以宣布對默認系統的更改: NSUserDefaultsDidChangeNotification

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM