0

I am a beginner in terms of xcode and objective-c and I am currently building an app that reads xml Files and compares their values to textfield values.

I have 2 classes. The first one is my View Controller where my textfields are. The second class is where I iterate through my xml files.

I simply want to be able to access the textfield's text my XML iterator class. It is important that I can save the text that has been entered in the textfield as a variable in my iterator class.

I attempted to do something like this, but it didn't work:

ViewController *viewcontroller = [[ViewController alloc]   initWithNibName:@"ViewController" bundle:nil];

viewcontroller.string = self.myTextField.text;

Help would be greatly appreciated since I have had trouble with this for a long time now.

Honza Zidek
  • 9,204
  • 4
  • 72
  • 118
  • Look into using a Singleton. Many examples can be found by Googling. – Stonz2 Jul 28 '14 at 13:31
  • 1
    You shoul check [this](http://stackoverflow.com/questions/626898/how-do-i-create-delegates-in-objective-c) question and answers. – modusCell Jul 28 '14 at 13:31
  • So the second class, that iterates through the XML files, is also derived from `UIViewController`? – Droppy Jul 28 '14 at 13:39
  • 1
    @mohacs I don't think delegation is the right way to implement this — it would most likely work, but much more cleaner approach from code structure point of view would be to stick to MVC pattern. See my answer below for details. – Rinat Khanov Jul 28 '14 at 14:07
  • @RinatKhanov agreed, stand correcting. A singleton class would be better solution then using protocol in this case. – modusCell Jul 29 '14 at 13:36
  • Did you figure this out? If so, please accept my answer below and close this question as resolved. – Rinat Khanov Aug 04 '14 at 15:55

1 Answers1

1

Let's return to the basics of MVC pattern (which stands for Model-View-Controller) — your view controller talks directly to your views and model (or any helpers, like XML iterator in our case). So most likely the right approach would be to give your XML iterator text values directly in your ViewController's implementation and update / reset XML iterator every time text field's value changes.

One way to implement this is to have a strong @property to your XML iterator in your ViewController class (create XML iterator instance once, then assign in to the property and use it later). Another common way is to implement your XML iterator as a singleton class.

It's hard to tell which option is better in your exact case (for example, you can also use protocols or even notifications). However, this general MVC-oriented approach described above works in most basic cases. For more, read about Model-View-Controller pattern — Apple Documentation is the right place to start.

Rinat Khanov
  • 1,566
  • 10
  • 32