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

时间:2013-11-12 11:49:19

标签: ios objective-c xamarin.ios

我是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#。

1 个答案:

答案 0 :(得分:8)

当然有更好的方法来实现这一目标,但让这个Obj-C代码到Xamarin.iOS C#进行几乎逐行转换:

sendEventUIApplication的一种方法。将它子类化是非常罕见的,请参阅UIApplication class reference上的子类化注释

一旦将其子类化,就必须指示运行时使用它,这是通过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");
    }
}

我将maxIdleTime替换为TimeSpan.FromHours (1)。否则,你将拥有与Obj-C相同的行为,包括bug(如果有的话)(虽然看起来不错)。