iOS:将ObjC代码转换为C#,如何知道应用程序闲置的时间

我是新的iOS开发,我正在使用monotouch开发iOS应用程序,我想知道应用程序闲置的时间,我得到了ObjC代码,但无法将其转换为C#。 这里是代码:

- (void)sendEvent:(UIEvent *)event { [super sendEvent:event]; // Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets. NSSet *allTouches = [event allTouches]; if ([allTouches count] > 0) { // allTouches count only ever seems to be 1, so anyObject works here. UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase; if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded) [self resetIdleTimer]; } } - (void)resetIdleTimer { if (idleTimer) { [idleTimer invalidate]; [idleTimer release]; } idleTimer = [[NSTimer scheduledTimerWithTimeInterval:maxIdleTime target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO] retain]; } - (void)idleTimerExceeded { NSLog(@"idle time exceeded"); } 

任何人都可以帮助我把这个转换成C#。

当然有更好的方法来实现这一点,但是我们来做一下这个Obj-C代码到Xamarin.iOS

sendEventUIApplication一个方法。 对它进行子类化是非常less见的,参见UIApplication类参考的 子类注释

一旦你将其分类,你必须指示运行时使用它,这是在Main.cs中的Main方法中Main.cs 。 以下是修改后的Main.cs现在的样子。

 public class Application { // This is the main entry point of the application. static void Main (string[] args) { UIApplication.Main (args, "MyApplication", "AppDelegate"); } } [Register ("MyApplication")] public class MyApplication : UIApplication { } 

注意类的Register属性,用作UIApplication.Main第二个参数。

现在,我们来翻译一下你的代码:

 [Register ("MyApplication")] public class MyApplication : UIApplication { public override void SendEvent (UIEvent uievent) { base.SendEvent (uievent); var allTouches = uievent.AllTouches; if (allTouches.Count > 0) { var phase = ((UITouch)allTouches.AnyObject).Phase; if (phase == UITouchPhase.Began || phase == UITouchPhase.Ended) ResetIdleTimer (); } } NSTimer idleTimer; void ResetIdleTimer () { if (idleTimer != null) { idleTimer.Invalidate (); idleTimer.Release (); } idleTimer = NSTimer.CreateScheduledTimer (TimeSpan.FromHours (1), TimerExceeded); } void TimerExceeded () { Debug.WriteLine ("idle time exceeded"); } } 

我用TimeSpan.FromHours (1)replace了maxIdleTime 。 否则,你将会有和Obj-C一样的行为,包括bug(尽pipe如此)。