我必须调用一个反复出现的方法,换句话说,该方法将调用自己。
同时,我必须有一个控制变量,该方法将使用。
首先,我会考虑像controlIndex那样声明一个ivar,然后在方法中使用它,如下所示:
// declared on .h
NSUInteger controlIndex;
// later on the program...
controlIndex = 100;
[self doItBaby];
...
- (void)doItBaby {
NSArray *subNodes = [node children];
if ([subNodes count] == 0) return;
for (id oneNode in subNodes) {
if ([oneNode isABomb]) {
[oneNode markNodeWithIndex:controlIndex];
controlIndex ++;
}
[self doItBaby];
}
}这段代码将完成这项工作,但我使用的是在主类头上声明的ivar。
我想知道是否有一种方法可以自我包含controlIndex变量,而不是在类头上使用这个变量。
发布于 2014-03-15 12:55:38
将您的方法重构为接受一个论点。
- (void)doItBaby:(NSUInteger)controlIndex {
NSArray *subNodes = [node children];
if ([subNodes count] == 0) return;
for (id oneNode in subNodes) {
if ([oneNode isABomb]) {
[oneNode markNodeWithIndex:controlIndex];
controlIndex ++;
}
[self doItBaby:controlIndex];
}
}您仍然需要向它发送一个初始值,并使用每个递归调用重新发送controlIndex变量,但是您的初始值不必是对整个类可见的实例变量。
[self doItBaby:100];发布于 2014-03-15 12:33:21
在static NSUInteger controlIndex中声明doItBaby
- (void)doItBaby {
static NSUInteger controlIndex = 100;
}https://stackoverflow.com/questions/22423822
复制相似问题