Kevin
Kevin

Reputation: 1479

Objective C - Make Method Call Itself Only Once

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).

Upvotes: 3

Views: 4859

Answers (4)

Mat
Mat

Reputation: 206879

The simplest thing to do is split that in two methods:

-(void) subMethodName
{
    action1;
    action2;
}

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

Or to use a loop of some form or other.

(What you have in your original code is infinite recursion - not a good thing in general.)

Upvotes: 3

Jacob Relkin
Jacob Relkin

Reputation: 163308

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();
   }

   //...
}

Upvotes: 15

N C
N C

Reputation: 539

You need to apply some logic on it. This can be using Bool Variable Or simply a count.

Take

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

Now just modify your method as follows

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

Upvotes: 1

MByD
MByD

Reputation: 137432

You can use static variable:

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

Upvotes: 6

Related Questions