Akshay
Akshay

Reputation: 151

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 ?

Upvotes: 0

Views: 857

Answers (2)

Josh Homann
Josh Homann

Reputation: 16347

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")

Upvotes: 1

Lal Krishna
Lal Krishna

Reputation: 16200

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

Upvotes: 1

Related Questions