I have an internal class that adoptsUIScrollViewDelegate
, but does not implement scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)
. I want to add this method to the class using class_addMethod
, but unfortunately run into a EXC_BAD_ACCESS
error when trying to assign a new value to targetContentOffset
.
Here is my code:
func extendDelegate(scrollViewDelegte: UIScrollViewDelegate) {
let block : @convention(block) (UIScrollView, CGPoint, UnsafeMutablePointer<CGPoint>) -> Void = { scrollView, velocity, targetContentOffset in
// EXC_BAD_ACCESS here.
// I can read the pointee and it does contain a valid CGPoint value,
// however assigning to it gives a crash.
targetContentOffset.pointee = .zero
}
class_addMethod(
type(of: scrollViewDelegte),
#selector(UIScrollViewDelegate.scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)),
imp_implementationWithBlock(block),
"v@:@{CGPoint=dd}^{CGPoint=dd}"
)
}
Any helps is greatly appreciated!
2
Answers
From
imp_implementationWithBlock
‘s documentation:I think you are missing self in parameters.
Rather than generating your own IMP and type encoding, I’d suggest you let the compiler do it for you, by creating a method normally, and transplanting it over:
Here’s a simpler standalone proof-of-concept: