0

SWITCHがオンのときに1秒ごとにコマンドを実行したいdoループがあります。

DO LOOPがない場合、コードは1回は正常に機能します。

ただし、LOOPを追加するとすぐに、View Controllerのラベルは更新されず、ストーリーボードの戻るボタンが機能せず、SWITCHがオフになりません。基本的に、DO LOOPはループを続けますが、画面上で何も機能せず、元に戻すこともできません。

私はそれを間違っていることを知っています。しかし、私は今何をしていません。どんな考えでもいただければ幸いです。

困ったコードを添付しました。

ありがとう、

 - (IBAction)roaming:(id)sender {
UISwitch *roamingswitch = (UISwitch *)sender;

BOOL isOn = roamingswitch.isOn;

if (isOn) {

    last=[NSDate date];

    while (isOn)
    {

        current = [NSDate date];

        interval = [current timeIntervalSinceDate:last];

    if (interval>10) {

    TheCommand.text=@"ON";

    [self Combo:sendcommand];

        last=current;


    }

    }

}

else
{
    TheCommand.text=@"OFF";

}

}

4

2 に答える 2

2

iOS と OSX はイベント ベースのシステムであり、メイン (UI) スレッドでこのようなループを使用してやりたいことを実行することはできません。そうしないと、実行ループの実行を許可せず、イベントの処理が停止します。

参照: Mac アプリ プログラミング ガイドのセクション「アプリのメイン イベント ループが相互作用を駆動する」。

あなたがする必要があるのは、NSTimer毎秒起動するタイマー( )を設定することです:

.h ファイル:

@interface MyClass : NSView     // Or whatever the base class is
{
    NSTimer *_timer;
}

@end

.m ファイル:

@implementation MyClass


- (id)initWithFrame:(NSRect)frame   // Or whatever the designated initializier is for your class
{
    self = [super initInitWithFrame:frame];
    if (self != nil)
    {
        _timer = [NSTimer timerWithTimeInterval:1.0
                                         target:self
                                       selector:@selector(timerFired:)
                                       userInfo:nil
                                        repeats:YES];
    }
    return self;
}

- (void)dealloc
{
    [_timer invalidate];

    // If using MRR ONLY!
    [super dealloc];
}

- (void)timerFired:(NSTimer*)timer
{
    if (roamingswitch.isOn)
    {
        TheCommand.text=@"ON";
        [self Combo:sendcommand];
    }
}

@end
于 2013-02-11T13:33:24.593 に答える