[英]In obj-c/iPhone SDK how do I get a mthod to call itself?
I have a method that I need to repeat until a certain condition is met. 我有一种方法需要重复执行,直到满足特定条件为止。 I am using an statement like:
我正在使用类似这样的语句:
if (condition is not met){ 如果(不满足条件){
run this method again 再次运行此方法
} else { }其他{
} }
But I don't know how to 'run this method again'. 但我不知道如何“再次运行此方法”。 The method is called runAction so i tried [self runAction] but it caused a runtime error.
该方法称为runAction,所以我尝试了[self runAction],但它导致运行时错误。
Any help appreciated. 任何帮助表示赞赏。
Thanks 谢谢
Calling a method from within itself is legal, but you may end up with a stack overflow if you call unto infinity 从内部调用方法是合法的,但如果调用无限,则可能会导致堆栈溢出
- (void)runAction
{
[self runAction]; // Stack Overflow on this line ;)
}
rpetrich has given you the right answer, but have you considered using a loop instead? rpetrich给了您正确的答案,但是您是否考虑过使用循环?
while (condition is not met)
{
// logic that affects condition.
}
Also if 'condition' is dependent on outside forces (user input, downloading, etc) then neither of these are correct and you could cause a deadlock - this is where two cases cannot complete because they are both waiting on the other. 同样,如果“条件”取决于外部力量(用户输入,下载等),那么这些都不正确,并且可能导致死锁-这是两种情况无法完成的原因,因为它们都在等待对方。
If this is the case you should use a timer that checks for the condition every XXX seconds or so. 如果是这种情况,则应使用计时器,每隔XXX秒左右检查一次条件。 The easiest way is to use the 'performSelector' function which can be used to trigger a call after a specified amount of time.
最简单的方法是使用“ performSelector”功能,该功能可用于在指定的时间后触发呼叫。
Eg 例如
-(void)someFunc
{
if(!condition)
{
[self performSelector:@selector(someFunc) withObject:nil afterDelay:1.0];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.