我这里有问题......
按下按钮后,我想要一个循环运行,直到达到条件:
- (IBAction)buttonclick1 ...
if ((value2ForIf - valueForIf) >= 3) { ...
我希望循环运行直到
((value2ForIf - valueForIf) >= 3)
然后执行与IF语句关联的代码。
我想要实现的是在继续代码之前继续检查上述陈述是否为真的程序。除此之外,IF下面还有一个else语句,但我不知道这是否会影响循环。
我不确定此处所需的循环格式以及我尝试的所有内容都会导致错误。任何帮助将不胜感激。
斯图
答案 0 :(得分:2)
除非运行紧密循环,否则会阻止您的应用执行,除非在另一个线程上运行,您可以使用NSTimer以您选择的时间间隔调用方法并检查该方法中的条件。如果满足条件,则可以使计时器无效并继续。
答案 1 :(得分:2)
- (IBAction)buttonclick1 ...
{
//You may also want to consider adding a visual cue that work is being done if it might
//take a while until the condition that you're testing becomes valid.
//If so, uncomment and implement the following:
/*
//Adds a progress view, note that it must be declared outside this method, to be able to
//access it later, in order for it to be removed
progView = [[MyProgressView alloc] initWithFrame: CGRectMake(...)];
[self.view addSubview: progView];
[progView release];
//Disables the button to prevent further touches until the condition is met,
//and makes it a bit transparent, to visually indicate its disabled state
thisButton.enabled = NO;
thisButton.alpha = 0.5;
*/
//Starts a timer to perform the verification
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: 0.2
target: self
selector: @selector(buttonAction:)
userInfo: nil
repeats: YES];
}
- (void)buttonAction: (NSTimer *) timer
{
if ((value2ForIf - valueForIf) >= 3)
{
//If the condition is met, the timer is invalidated, in order not to fire again
[timer invalidate];
//If you considered adding a visual cue, now it's time to remove it
/*
//Remove the progress view
[progView removeFromSuperview];
//Enable the button and make it opaque, to signal that
//it's again ready to be touched
thisButton.enabled = YES;
thisButton.alpha = 1.0;
*/
//The rest of your code here:
}
}
答案 2 :(得分:1)
根据你的说法,你想要的是一个while循环
while( (value2ForIf - valueForIf) < 3 ) { ...Code Here... }
只要值的差值小于3,这将在大括号中运行代码,这意味着它将运行直到它们的差值为3或更大。但正如亚萨里恩所说。这是一个坏主意,因为你将阻止你的程序。如果代码本身正在更新值,那很好。但是,如果用户正在通过某些UI更新它们,则while循环将阻止UI并且不允许用户输入任何内容。