Objective C - Make Method Call Itself Only Once
cocoa, objective-c
Solution
If you mean to say only once during the entire lifetime of the application, you can use `dispatch_once`, like this:
-(void)methodName
{
action1;
action2;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[self methodName];
});
}
If, however, you meant for the method to execute `action1` and `action2` twice per invocation, you have two options:
1) Wrap that functionality in another method:
- (void)executeMethod {
[self methodName];
[self methodName];
}
2) Even simpler, wrap it in a loop:
- (void)methodName {
for(int i = 0; i < 2; ++i) {
action1();
action2();
}
//...
}
Problem
If I have this method: ``` -(void) methodName { action1; action2; [self methodName]; } ``` I want the [self methodName] call to be done only once, therefore the method to be called only twice consecutively. Can this be done? Not sure where in the docs I should be looking. Whenever method 'methodName' is called, then when action1 and action2 are done, it should call itself again, but only once. The way it is done in the sample code I have written is going on forever (I am guessing).