Goal C - Make a call-only method

If I have this method:

-(void) methodName
{
    action1;
    action2;
    [self methodName];
}

I want the [self methodName] call to be executed only once, so the method should only be called twice in a row. It can be done? Not sure where in the docs I should look.

When the methodName method is called, then when actions 1 and action2 are executed, it must call itself again, but only once. The way this is done in the code sample I wrote goes on forever (I guess).

+3
source share
4 answers

If you want to say only once during the entire duration of the application, you can use dispatch_once, for example:

-(void)methodName
{
    action1;
    action2;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
       [self methodName];
    });
}

, , , action1 action2 , :

1) :

- (void)executeMethod {
    [self methodName];
    [self methodName];
}

2) , :

- (void)methodName {
   for(int i = 0; i < 2; ++i) {
      action1();
      action2();
   }

   //...
}
+14

:

-(void) methodName
{
    static BOOL called = NO;
    if (called == NO)
    {
        called = YES;
        [self methodName];
    }
    else
    {
        called = NO;
    }
}
+5

The simplest task is to divide this into two methods:

-(void) subMethodName
{
    action1;
    action2;
}

-(void) methodName
{
    [self subMethodName];
    [self subMethodName];
}

Or use a loop of some form.

(What you have in your source code is infinite recursion is generally not good.)

+3
source

You need to apply some logic. It could be using a Bool variable or just an account.

To accept

int Count=0; //as a global variable.

Now just change your method as follows

-(void) methodName
{
    Count++;
    action1;
    action2;
    if(Count==1)
       [self methodName];
}
+1
source

All Articles