2013-02-11 50 views
0

我有一个do循环,我想在SWITCH打开时每隔1秒执行一次命令。X循环视图控制器没有在Do循环中更新

该代码工作正常,当我没有DO LOOP。

但是,只要添加LOOP,视图控制器中的标签都不会更新,故事板的后退按钮不起作用,并且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) { 

    [email protected]"ON"; 

    [self Combo:sendcommand]; 

     last=current; 


    } 

    } 

} 

else 
{ 
    [email protected]"OFF"; 

} 

}

+0

请显示“Do循环”代码 – Spectravideo328 2013-02-11 13:01:15

回答

1

iOS和OSX是基于事件的系统,你不能使用这样的循环主(UI)线程做你想做的事,否则您不允许运行循环运行并且事件停止处理。

请参阅:Mac App Programming Guide“应用程序的主要事件循环驱动交互”部分。

你需要的是建立一个定时器(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) 
    { 
     [email protected]"ON"; 
     [self Combo:sendcommand]; 
    } 
} 

@end 
+0

感谢您的快速响应。一旦遇到问题,我就尽可能多地假设,但需要一些指导。我会去做。 – Belboz 2013-02-11 13:40:14