views:

52

answers:

1

Let's say I create a new project. I now add two text fields to the view controller in Interface Builder. I want to respond to delegate events that the text fields create, however, I don't want to have the main view controller to act as the delegate for both text fields. Ideally I want a separate file for each text field that acts as the delegate. Each of these objects also needs to be able to interact with the main view controller.

My question is how I would set this up and link everything correctly?

I tried creating a new class that inherits from NSObject and implements UITextFieldDelegate. I then added an instance variable called "viewController" of the same type of my view controller and marked it with IBOutlet (this required me to add #import "myViewcontroller.h").

I then went to Interface Builder and opened up my view controller which contains the two edit boxes. I added an NSObject to the form and changed it's type to be of the new class I created. I set its viewController property to the File's Owner, and set one of the textbox's delegate properties to point to this new object I created.

Now when I run the program, it crashes when I touch the text box. It gives the error EXC_BAD_ACCESS. I'm guessing I didn't link stuff correctly in IB.

Some things I'm not sure about which might be the problem:
Does IB automatically know to create an instance of the class just by placing the NSObject in the ViewController? Can it properly assign the viewController property to an instance of itself even though it is creating itself at the same time? Maybe the problem is that this new object is not being retained by anything?

+2  A: 

You’re right. Your delegate object is not being retained. On iPhone OS, each object in a nib file is initialized with a retain count of 1, then autoreleased. If nothing retains the object again, it will eventually be released.

Add a property to your view controller class and connect it to the instance of the delegate. As long as you define the property correctly, the view controller will retain the object, and everything will work as expected.

Todd Yandell
Thanks for the answer, it works. Because it would normally cause a circular unit reference since both files refer to each other, I just added @class in the new file created. For more information, see http://stackoverflow.com/questions/322597/objective-c-class-vs-import
Senseful
That’s generally the preferred way to reference other classes from a header file. I try to always use @class in the header file and #import in the actual .m file so I never need to come back and change it.
Todd Yandell