ios – 如何将“method_getImplementation”和“method_setImplementation”移植到MonoTouch?

前端之家收集整理的这篇文章主要介绍了ios – 如何将“method_getImplementation”和“method_setImplementation”移植到MonoTouch?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
从我的问题: Without subclassing a UIView or UIViewController: possible to catch if a subview was added?

我想知道如何从MonoTouch的答案中移植代码.它基本上用一个新方法替换一个方法,然后在没有子类化的情况下调用方法.是否有可能让这个指针在MonoTouch中工作?

  1. //Makes views announce their change of superviews
  2. Method method = class_getInstanceMethod([UIView class],@selector(willMoveToSuperview:));
  3. IMP originalImp = method_getImplementation(method);
  4.  
  5. void (^block)(id,UIView*) = ^(id _self,UIView* superview) {
  6. [_self willChangeValueForKey:@"superview"];
  7. originalImp(_self,@selector(willMoveToSuperview:),superview);
  8. [_self didChangeValueForKey:@"superview"];
  9. };
  10.  
  11. IMP newImp = imp_implementationWithBlock((__bridge void*)block);
  12. method_setImplementation(method,newImp);

解决方法

这似乎是我们提供劫持方法的通用机制的一个很好的候选者.以下是纯C#代码的实现,您可以在此期间使用它:
  1. [DllImport ("/usr/lib/libobjc.dylib")]
  2. extern static IntPtr class_getInstanceMethod (IntPtr classHandle,IntPtr Selector);
  3. [DllImport ("/usr/lib/libobjc.dylib")]
  4. extern static Func<IntPtr,IntPtr,IntPtr> method_getImplementation (IntPtr method);
  5. [DllImport ("/usr/lib/libobjc.dylib")]
  6. extern static IntPtr imp_implementationWithBlock (ref BlockLiteral block);
  7. [DllImport ("/usr/lib/libobjc.dylib")]
  8. extern static void method_setImplementation (IntPtr method,IntPtr imp);
  9.  
  10. static Func<IntPtr,IntPtr> original_impl;
  11.  
  12. void HijackWillMoveToSuperView ()
  13. {
  14. var method = class_getInstanceMethod (new UIView ().ClassHandle,new Selector ("willMoveToSuperview:").Handle);
  15. original_impl = method_getImplementation (method);
  16. var block_value = new BlockLiteral ();
  17. CaptureDelegate d = MyCapture;
  18. block_value.SetupBlock (d,null);
  19. var imp = imp_implementationWithBlock (ref block_value);
  20. method_setImplementation (method,imp);
  21. }
  22.  
  23. delegate void CaptureDelegate (IntPtr block,IntPtr self,IntPtr uiView);
  24.  
  25. [MonoPInvokeCallback (typeof (CaptureDelegate))]
  26. static void MyCapture (IntPtr block,IntPtr uiView)
  27. {
  28. Console.WriteLine ("Moving to: {0}",Runtime.GetNSObject (uiView));
  29. original_impl (self,uiView);
  30. Console.WriteLine ("Added");
  31. }

猜你在找的iOS相关文章