AdamM
AdamM

Reputation: 4430

Objective-c Adding dynamic elements with necessary delegate methods

I have an application where each screen will be added dynamically, along with all the elements on the screen, i.e, table, textfields etc. Each viewController will be using the same NIB, basically I loop through the JSON and for every new screen, I create a new ViewController object and add it to an array, and I do the same thing for the objects to be added to the screen.

The thing is, one screen may need a tableView delegate methods, another may need the text field delegate methods. If I don't have the delegates implemented in interface file, then I can't do this

 textField.delegate = self;

or

tableView.delegate = self;
tableView.dataSource = self;

as it will flag an error.

Would it be bad practice, just to add all the delegate methods that I am likely to have, i.e.

@interface Testing : UIViewController<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate, UITextViewDelegate, UIWebViewDelegate>

and then implement all the methods, that way it would only call them if they were needed. Or would this be bad idea?

Or is there a better way to set this up?

Any information would be much appreciated.

Upvotes: 0

Views: 235

Answers (2)

nkongara
nkongara

Reputation: 1229

Yes, You can implement the required delegate methods and they will be called whenever required. Its always the preferred approach.

Upvotes: 1

zoul
zoul

Reputation: 104065

One shotgun approach is to strip the type off the delegate:

textField.delegate = (id) self;

If the delegate is somehow guaranteed to respond to the messages as required by the protocol, then everything will work fine. Whether this is an ugly hack or an elegant solution depends on the details of your problem.

Upvotes: 1

Related Questions