【问题标题】:KVO broken in iOS 9.3KVO 在 iOS 9.3 中被破坏
【发布时间】:2016-03-24 04:54:01
【问题描述】:

这可能是 iOS 9.3(发行版)中的一个严重错误。

在向[NSUserDefaults standardUserDefaults] 添加单个观察者时,我注意到响应方法-observeValueForKeyPath:ofObject:change:context: 被多次调用。

在下面的简单示例中,每按下一次 UIButton,observeValueForKeyPath 就会触发两次。在更复杂的示例中,它会触发更多次。它仅存在于 iOS 9.3(sim 卡和设备上)。

这显然会对应用造成严重破坏。其他人有同样的经历吗?

// ViewController.m (barebones, single view app)

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"viewDidLoad");
    [[NSUserDefaults standardUserDefaults] addObserver:self forKeyPath:@"SomeKey" options:NSKeyValueObservingOptionNew context:NULL];
}

- (IBAction)buttonPressed:(id)sender {
    NSLog(@"buttonPressed");
    [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"SomeKey"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    NSLog(@"observeValueForKeyPath: %@", keyPath);
} 

【问题讨论】:

  • NSUserDefaults 键值是否可观察?我没有看到任何证据表明它是。你正在做一些你没有理由去做的事情。如果它停止工作,你不能抱怨。
  • @matt 我没有考虑到这一点。然而,我在 NSUserDefaults.h 中发现了以下内容:NSUserDefaults can be observed using Key-Value Observing for any key stored in it.
  • @Matt,我在看同一个NSUserDefaults.h吗?我找不到您在此标题中发布的评论。
  • @BorisVerebsky 你在检查什么版本的 Xcode?也许它是 Xcode 7.3/iOS 9.3 中的新功能。
  • @Matt,XCode 7.2,将仔细检查 XCode 7.3/iOS 9.3

标签: ios objective-c key-value-observing ios9.3


【解决方案1】:

是的,我也遇到了这个问题,这似乎是一个错误,下面是我目前正在使用的快速解决方法,直到这个问题得到修复。希望对你有帮助!

另外澄清一下,由于 iOS 7 KVO 与 NSUserDefaults 配合得很好,而且正如 Matt 所说,它肯定是可观察的键值,它在 iOS 9.3 SDK 的 NSUserDefaults.h 中明确编写:“NSUserDefaults 可以使用观察对存储在其中的任何键进行键值观察。”

#include <mach/mach.h>
#include <mach/mach_time.h>

@property uint64_t newTime;
@property uint64_t previousTime;
@property NSString *previousKeyPath;

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    //Workaround for possible bug in iOS 9.3 SDK that is causing observeValueForKeyPath to be called multiple times.
    newTime = mach_absolute_time();
    NSLog(@"newTime:%llu", newTime);
    NSLog(@"previousTime:%llu", previousTime);

    //Try to avoid duplicate calls
    if (newTime > (previousTime + 5000000.0) || ![keyPath isEqualToString:previousKeyPath]) {
        if (newTime > (previousTime + 5000000.0)) {
            NSLog(@"newTime > previousTime");
            previousTime = newTime;
            NSLog(@"newTime:%llu", newTime);
            NSLog(@"previousTime:%llu", previousTime);
        }
        if (![keyPath isEqualToString:previousKeyPath]) {
            NSLog(@"new keyPath:%@", keyPath);
            previousKeyPath = keyPath;
            NSLog(@"previousKeyPath is now:%@", previousKeyPath);
        }
        //Proceed with handling changes
        if ([keyPath isEqualToString:@“MyKey"]) {
            //Do something
        }
    }
}

【讨论】:

  • 很好的答案。为我工作!请注意您的@“MyKey”如何在 Xcode 抱怨的 @ 之后包含一个奇怪的引用
  • 这在 swift 4 和 iOS 11.4 中不起作用。仍会触发多项更改。
【解决方案2】:

向[NSUserDefaults standardUserDefaults] 添加单个观察者时,我注意到响应方法-observeValueForKeyPath:ofObject:change:context: 被多次调用

这是一个已知问题,在 iOS 11 和 macOS 10.13 中修复为 reported(Apple 提供)。

【讨论】:

  • 嗨,医生在哪里?
  • @frank developer.apple.com/library/content/releasenotes/Foundation/… “这也应该纠正向观察者传递某些更改的重复通知”——正是 OP 抱怨的行为。
  • 感谢您的回复。
  • 我认为这个问题在 MacOS 10.13 中没有得到解决。我的观察者在 NSUserDefaults 中设置一个值的 1 次按钮单击被调用 3 次。我已验证该按钮仅触发一次,该值仅设置一次并且我仅注册一次。检查通过针对部署目标 10.13 构建来尝试此操作。没有区别。
  • @CliffRibaudo 感谢您的报告。请向 Apple 提交错误报告!我不能确定发行说明是否打算解决这个问题,但看起来确实如此。如果他们还没有解决这个问题,他们无论如何都需要知道它。
【解决方案3】:

为 MacOS (10.13) 添加这个答案肯定有错误获取 NSUserDefault Keys 的 KVO 的多个通知,并且还解决了弃用问题。最好使用经过纳秒的计算来获取您正在运行的机器。这样做:

#include <mach/mach.h>
#include <mach/mach_time.h>
static mach_timebase_info_data_t _sTimebaseInfo;

uint64_t  _newTime, _previousTime, _elapsed, _elapsedNano, _threshold;
NSString  *_previousKeyPath;

-(BOOL)timeThresholdForKeyPathExceeded:(NSString *)key thresholdValue:(uint64_t)threshold
{
   _previousTime = _newTime;
   _newTime = mach_absolute_time();

    if(_previousTime > 0) {
        _elapsed = _newTime - _previousTime;
        _elapsedNano = _elapsed * _sTimebaseInfo.numer / _sTimebaseInfo.denom;
    }

    if(_elapsedNano > threshold || ![key isEqualToString:_previousKeyPath]) {
        if(![key isEqualToString:_previousKeyPath]) _previousKeyPath = key;
            return YES;
        }
        return NO;
    }
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if(![self timeThresholdForKeyPathExceeded:keyPath thresholdValue:5000000]) return;  // Delete this line of MacOS bug ever fixed
    }
    // Else this is the KeyPath you are looking for Obi Wan, process it.
}

这是基于这个 Apple Doc 的清单 2: https://developer.apple.com/library/content/qa/qa1398/_index.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-09
    • 2017-06-13
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2023-03-15
    相关资源
    最近更新 更多