Search code examples
objective-ciosdelegatesuitextfielduitextfielddelegate

UITextFieldDelegate Causes Exception


Simple Case. I want to create a UIViewController displaying and reacting to the input of a simple UITextField.

  1. I created a UIViewController including the xib file.
  2. In Interface Builder I added a View and a containing UITextField.
  3. The File's Owner is set to the according class name that contains the logic "CardViewController".
  4. The File Owner points to the View as view.
  5. The text field uses the File's Owner as delegate.

It looks like this...

enter image description here

The view is being displayed correctly, but as soon as I tap the textfield the application crashes with an exception "EXC_BAD_ACCESS...."

My guess is that there's something wrong with the assignement of the delegate, but I have problems finding the issue. Any idea? What did I miss?


Further Findings. When I instantiate this viewcontroller directly in the AppDelegate the delegation of the UITextField actually works!!

But what I actually plan to do to create an instance of a "BoardViewController" class first which then creates "CardViewController" objects. Having this kind nesting causes the delegation to fail.

As a reference. In my App Delegate:

BoardViewController *bvc = [[BoardViewController alloc] init];
[self.window setRootViewController:bvc];

in the Board Class I have a "add" button that triggers the creation of the CardViewControllers

-(void) addCard:(id)touchEvent{
    NSLog(@"<Board> Add");
    CardViewController *cvc = [[CardViewController alloc]init];
    [self.view addSubview:cvc.view];
}

and then the CardViewController looks as mentioned at first with the delegation being set in the xib.


Solution

  • It looks like I found my solution. Instead of just adding the view of the CardViewController as subview I also needed to add it as ChildViewController.

    In the parent BoardViewController

    -(void) addCard:(id)touchEvent{
        CardViewController *cvc = [[CardViewController alloc]init];
        [self addChildViewController:cvc];
        [self.view addSubview:cvc.view];
    }
    

    Then the delegate call works. Yay.