Search code examples
iosobjective-cios6

Sending data between classes ios?


Ok so this is the situation I have.

I have created new project using master detail template and in MasterViewController I have table and cell which was displaying title only. I modified cell to be custom and added two text-fields. My app requirement is to plot graph real-time as soon user enters point in textfield. Graph is displayed in detail view and that part works fine (Graph plotting).

Now my problem is how to transfer data from the class which is not uiview controller. MasterViewController is subclass of UITableViewController but to create outlets for the textfields I have to have subclass of UITableViewCell. So I created new class CellData (subclass of UITableViewCell) and I can get values from textfields real-time using IBAction didFinishEditing and IBOutlets for the textfields and data is automatically added to array.

Now how should I push this array to MasterViewController and then further to class GraphDraw which will actually draw graph. What I did is to create global class which I suspect is not ideal solution. Should I create three way protocol and delegate solution or maybe model class as someone suggested?

So far all the protocol and delegate tutorials were focused on viewControllers and I have no problems with that but they don't quite work for my situation. And with model class which is subclass of NSObject I cannot directly get cell data. Now I apologise if question is long but I am beginner and I am trying to figure out best way to solve these problems. Any help is appreciated.


Solution

  • Delegation is the way to go here. This setup though is a little confusing and is probably why the resources out there are not exactly what you are looking for.

    First you will need a delegate that can send messages from your UITableViewCell subclass to the master UITableViewController. Take the following for example:

    CellData

    @protocol JDPlotCellDelegate <NSObject>
    
    - (void)didFinishEditingWithData:(id)someData;
    
    @end
    

    Now when the UITextField sends its didFinishEditing delegate message:

    - (void)textFieldDidEndEditing:(UITextField *)textField {
    
        [self.delegate didFinishEditingWithData:textField.text];
    }
    

    Simple so far right?

    Next, your master tableview controller needs to implement the delegate (and make sure the cells have the delegate property hooked up!)

    MasterViewController

    - (void)didFinishEditingWithData:(id)someData {
    
        [self.detailViewController plotSomeData:someData];
    }
    

    Then since the master has a reference to the details view controller it can be as simple as declaring a public method - (void)plotSomeData:(id)someData; on the detail view controller that can take the data and plot it.

    Hope this helps!