Files
swift-mirror/stdlib/objc/Foundation/KVO.swift
Ted Kremenek 3d248270ca Add prototype for KVO API overlay ("KVOContext") to NSObject, and provide test case.
This change adds a new variant of "addObserver:forKeyPath:options:context:"
that takes a "KVOContext" instead of an unsafe void*.  The variant
delegates to the original method, but first 'retain's the object
before turning it into an unsafe pointer.  The API is then matched
with a variant of 'removeObserver:forKeyPath:context:' which
delegates to the original method and then 'release's it.

This vision here is that Swift clients of this API will use this
variant, and not the unsafe one.  A refinement (later) is to
not expose the original methods at all, and provide a new method
'observeValueForKeyPath:ofObject:change:kvoContext:' that implements
a thunk that delegates to 'observeValueForKeyPath:ofObject:change:context:'
and does the void* cast (which the code in the test case does).

This needs to go through API review; names are strawman names.

Swift SVN r17325
2014-05-03 20:06:28 +00:00

47 lines
1.6 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// FIXME: Make a nested class of 'NSObject'. Currently symbols
// are not being generated during compilation when it is a nested class.
class KVOContext {
class func fromVoidContext(context: CMutableVoidPointer) -> KVOContext {
return reinterpretCast(context.value)
}
}
extension NSObject {
func removeObserver(observer: NSObject!,
forKeyPath keyPath: String!,
kvoContext: KVOContext)
{
let ptr = CMutableVoidPointer(kvoContext, reinterpretCast(kvoContext))
self.removeObserver(observer,
forKeyPath: keyPath,
context: ptr)
Unmanaged(kvoContext).release()
}
func addObserver(observer: NSObject!,
forKeyPath keyPath: String!,
options: NSKeyValueObservingOptions,
kvoContext: KVOContext)
{
let ptr = CMutableVoidPointer(kvoContext, reinterpretCast(kvoContext))
Unmanaged(kvoContext).retain()
self.addObserver(observer,
forKeyPath: keyPath,
options: options,
context: ptr)
}
}