Shivbaba's son
Shivbaba's son

Reputation: 1369

How can I stop the function recursion in Objective C?

I have one text field.

Below function is attached to an UI event "editing changed" from txtfield's IB.

The function is recursive as obvious I am changing the textfield so it will call

again and again is there any thing , I can stop the function after calling it once.

So,I want to stop this looping function..

-(IBAction) testEvents:(id) sender
{ 

    txtEditAmount.text=[txtEditAmount.text substringToIndex:([txtEditAmount.text length]-1)];




}

Upvotes: 0

Views: 1234

Answers (4)

Narayana Rao Routhu
Narayana Rao Routhu

Reputation: 6323

Implement this method

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
  return YES;//it will allow edit to you if NO it will not allow to you
//return NO;when don,t want call that
}

Upvotes: 1

user244343
user244343

Reputation:

Rather than using that event callback, try implementing the UITextFieldDelegate method textFieldDidEndEditing:, like so:

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    textField.text = [textField.text substringToIndex:
                      [txtEditAmount.text length] - 1];
}

So it will cut off the last character only when the user stops editing the field. Depends what you're trying to do though, I guess. If you're trying to backspace whatever they type, for example, a password field which stays blank but still captures the characters the user types, instead implement the protocol method textField:shouldChangeCharactersInRange:replacementString: like this:

- (BOOL)textField:(UITextField *)textField
  shouldChangeCharactersInRange:(NSRange)range
  replacementString:(NSString *)string
{
    [enteredString appendString:string]; // store the character the user typed
    return NO; // leave the field blank
}

Upvotes: 2

Nekto
Nekto

Reputation: 17877

My variant

-(IBAction) testEvents:(id) sender
{ 
    static BOOL flag = NO;
    if (flag) {flag=NO; return;}
    flag = YES;
    txtEditAmount.text=[txtEditAmount.text substringToIndex:([txtEditAmount.text length]-1)];
}

Upvotes: 3

icktoofay
icktoofay

Reputation: 129019

You could use a static boolean.

-(IBAction) testEvents:(id) sender
{
    static BOOL programmaticallyChanged=NO;
    if(programmaticallyChanged) {
        return;
    }
    programmaticallyChanged=YES;
    txtEditAmount.text=[txtEditAmount.text substringToIndex:([txtEditAmount.text length]-1)];
    programmaticallyChanged=NO;
}

Upvotes: 1

Related Questions