c# - 如何使用 MonoTouch.ObjCRuntime.Selector 和 Perform Selector 发送参数

标签 c# iphone ios xamarin.ios monodevelop

这是我找到的一个例子,但他们忽略了实际发送参数。

this.PerformSelector(new MonoTouch.ObjCRuntime.Selector("_HandleSaveButtonTouchUpInside"),null,0.0f);

[Export("_HandleSaveButtonTouchUpInside")]
    void _HandleSaveButtonTouchUpInside()
    {
...
}

我希望能够做这样的事情:

this.PerformSelector(new MonoTouch.ObjCRuntime.Selector("_HandleSaveButtonTouchUpInside"),null,0.0f);

[Export("_HandleSaveButtonTouchUpInside")]
    void _HandleSaveButtonTouchUpInside(NSURL url, NSData data)
    {
...
}

如何更改 PerformSelector 调用以将参数发送到方法?

最佳答案

MonoTouch docs指示该方法映射到 Obj-C 选择器 performSelector:withObject:afterDelay , 它只支持调用带有单个参数的选择器。

处理此问题的最佳方法取决于您需要做什么。处理此问题的一种典型方法是将参数作为属性/字段放在单个 NSObject 上,然后将目标修改为具有单个参数,并从该方法中提取真正的参数。如果您使用自定义 MonoTouch 对象执行此操作,则必须注意收集托管对等点的 GC,如果托管代码中没有任何内容保留对它的引用的话。

更好的解决方案取决于您的具体使用方式。例如,在您的示例中,您可以直接调用 C# 方法,例如

_HandleSaveButtonTouchUpInside (url, data);

如果出于某种原因需要通过 Obj-C 发送,但不需要延迟,请使用 MonoTouch.ObjCRuntime.Messaging ,例如

MonoTouch.ObjCRuntime.Messaging.void_objc_msgSend_IntPtr_IntPtr (
    target.Handle,
    MonoTouch.ObjCRuntime.Selector.GetHandle ("_HandleSaveButtonTouchUpInside"),
    arg0.Handle,
    arg1.Handle);

如果你需要延迟,你可以使用 NSTimer . MonoTouch 对此添加了特殊支持以使用 NSAction委托(delegate),因此您可以使用 C# lambda 安全地捕获参数。

NSTimer.CreateScheduledTimer (someTimespan, () => _HandleSaveButtonTouchUpInside (url, data));

关于c# - 如何使用 MonoTouch.ObjCRuntime.Selector 和 Perform Selector 发送参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10475415/

相关文章:

c# - 更改进程优先级不起作用

c# - 如何使用 EventBuilder 创建事件?

ios - React Native 0.40.0 : RCTBundleURLProvider. h” 找不到文件 - AppDelegate.m

ios - 如何将可拖动对象放置在目标对象的中心

ios - Realm 查询 'where before date'

c# - PropertyGrid 的替代品?请听我说完

c# - 使 ASP.NET cookie 安全

iphone - Obj-C,在 View 中带有警报 View /进度指示的线程安全进程,可以从 applicationWillEnterForeground <= iOS4? 调用

iphone - 自定义 UITableViewCells

ios - XCode 6.3 Beta 将 iOS 8.3b 设备显示为 "ineligible"