简体   繁体   中英

Writing Kvo context in Swift

In ObjC

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

contentOffset is UIScrollView property.

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 ? or How can i write kKVOContext in swift ?

You could use swift 4's new feature

// 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; context is used with being initalized. In Swift it will be initialized to 0. Anyways, the context is for you to use. 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. 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; it defaults to nil if you aren't using it: self.superview?.removeObserver(self.parent!, forKeyPath: "contentOffset")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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