简体   繁体   English

在Swift中编写Kvo上下文

[英]Writing Kvo context in Swift

In ObjC ObjC

static void * const kKVOContext = (void*)&kKVOContext;
[self.superview removeObserver:self.parent forKeyPath:NSStringFromSelector(@selector(contentOffset)) context:kKVOContext];

contentOffset is UIScrollView property. contentOffsetUIScrollView属性。

I have written this into swift as- 我已将其写成-

Swift 迅速

 var kKVOContext = UnsafeMutableRawPointer.allocate(bytes: 4 * 4, alignedTo: 1)
 self.superview?.removeObserver(self.parent!, forKeyPath: NSStringFromSelector(#selector(getter: UIScrollView.contentOffset)), context: &kKVOContext)

So in Swift Is this correct way or it should be diffrent UnsafeMutableRawPointer ? 所以在Swift中,这是正确的方法还是应该与UnsafeMutableRawPointer不同? or How can i write kKVOContext in swift ? 或如何快速编写kKVOContext

You could use swift 4's new feature 您可以使用Swift 4的新功能

// Setting up KVO
 observation = scrollView.observe(\.contentOffset, changeHandler: { (object, change) in
       print("Updated Value: \(object.contentOffset)")
 })

 // Deiniting or invalidating the observation token ends the observation
 observation.invalidate()

 // After invalidating KVO doesn't trigger anymore

This Objective C code is bad; 这个Objective C代码很糟糕; context is used with being initalized. 上下文被用于初始化。 In Swift it will be initialized to 0. Anyways, the context is for you to use. 在Swift中,它将初始化为0。无论如何,上下文供您使用。 Its an arbitrary value that lets you specify why you are observing this value or who is obversing this value, apart from the object and keypath. 它是一个任意值,可让您指定为什么观察此值或谁在观察此值(对象和键路径除外)。 Its basically a user cookie. 它基本上是一个用户cookie。 Thats why this code doesn't crash; 这就是为什么此代码不会崩溃的原因; the OS doesn't use the context, you do. 操作系统不使用上下文,而是使用上下文。 In Swift you can just pass in the reference to any reference type, or you can actually omit the parameter; 在Swift中,您可以将引用传递给任何引用类型,或者实际上可以省略参数; it defaults to nil if you aren't using it: self.superview?.removeObserver(self.parent!, forKeyPath: "contentOffset") 如果不使用它,则默认为nil: self.superview?.removeObserver(self.parent!, forKeyPath: "contentOffset")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM