使用Swift添加不带指针的KVO观察器

使用Swift添加不带指针的KVO观察器

本文介绍了使用Swift添加不带指针的KVO观察器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,我通常会使用以下内容:

In Objective-C, I would normally use something like this:

static NSString *kViewTransformChanged = @"view transform changed";
// or
static const void *kViewTransformChanged = &kViewTransformChanged;

[clearContentView addObserver:self
                       forKeyPath:@"transform"
                          options:NSKeyValueObservingOptionNew
                          context:&kViewTransformChanged];

我有两种重载方法可供选择,以添加KVO观察者,唯一的区别是上下文参数:

I have two overloaded methods to choose from to add an observer for KVO with the only difference being the context argument:

 clearContentView.addObserver(observer: NSObject?, forKeyPath: String?, options: NSKeyValueObservingOptions, context: CMutableVoidPointer)
 clearContentView.addObserver(observer: NSObject?, forKeyPath: String?, options: NSKeyValueObservingOptions, kvoContext: KVOContext)

在Swift不使用指针的情况下,我不确定如何取消引用指针以使用第一种方法.

With Swift not using pointers, I'm not sure how to dereference a pointer to use the first method.

如果我创建了自己的KVOContext常量以用于第二种方法,那么我最终会问这个问题:

If I create my own KVOContext constant for use with the second method, I wind up with it asking for this:

let test:KVOContext = KVOContext.fromVoidContext(context: CMutableVoidPointer)

CMutableVoidPointer和KVOContext有什么区别?有人可以给我一个例子,说明如何同时使用它们以及何时将它们用于另一个吗?

What is the difference between CMutableVoidPointer and KVOContext? Can someone give me an example how how to use them both and when I would use one over the other?

Apple的一名开发人员刚刚将其发布到了论坛上:KVOContext即将消失;现在,要使用全局引用作为上下文.

EDIT #2: A dev at Apple just posted this to the forums: KVOContext is going away; using a global reference as your context is the way to go right now.

推荐答案

现在Xcode 6 beta 3中不再使用KVOContext了,您可以执行以下操作.像这样定义全局(即不是类属性):

Now that KVOContext is gone in Xcode 6 beta 3, you can do the following. Define a global (i.e. not a class property) like so:

let myContext = UnsafePointer<()>()

添加观察者:

observee.addObserver(observer, forKeyPath: …, options: nil, context: myContext)

在观察者中:

override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafePointer<()>) {
    if context == myContext {
        …
    } else {
        super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
    }
}

这篇关于使用Swift添加不带指针的KVO观察器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 06:17