0

I have gone through many questions in here but is still unable to find a solution to my problem. I have a class named ModelClass and another class named ViewController and yet another called ViewController2. I have the following properties in ModelClass:

@property (assign) int DataFromVC1;
@property (assign) int DataFromVC2;

I have the data collected from VC1 and VC2 and I correctly displayed the required data using NSLog from the corresponding view controllers. But when I try to send DataFromVC1 to VC2, and use NSLog to display 'DataFromVC1' from within VC2, it is showing 0. But it is displaying the correct value when NSLog is called from VC1.

I used the following code segments to import the MainClass in the ViewController class implementations(just including the relevant parts):

#import "ModelClass.h"
@interface ViewController2 ()
{    
    ModelClass *MC;    
}
@implementation ViewController
....
- (void)viewDidLoad
{
    .....
    MC = [[ModelClass alloc]init];
}
<function that gets the data>
{
    .....
    NSLog(@"%d",MC.DataFromVC1);
    ....
}
<function that sets the data>
{
    .....
    MC.DataFromVC2 = requiredData;
    .....
}

And similar code in the other ViewController class as well. Why is the data set to zero while sending from one class to another? Thanks in advance.

paulmelnikow
  • 16,895
  • 8
  • 63
  • 114
Harikrishnan
  • 7,765
  • 13
  • 62
  • 113
  • I didn't understand all you have written, but if you want to make some interaction with few controllers in iOS I suggest you using `NSNotification`s. I find your code not very object-oriented. – Valentin Shamardin Jul 17 '13 at 14:04
  • Simply speaking, I need to set a value to property called DataFromVC1 declared in ModelClass from ViewController and access the value from ViewController2 but I can't. – Harikrishnan Jul 17 '13 at 14:07
  • 2
    Are you sure that the two view controllers hold the same instance of `ModelClass`? – Khanh Nguyen Jul 17 '13 at 14:12
  • If yes, the best practice is using singleton – Valentin Shamardin Jul 17 '13 at 14:13
  • I tried with singleton but yet the same result. Yes, the two view controllers must use the same instance of ModelClass. How can I do it with Singleton? I tried `http://www.galloway.me.uk/tutorials/singleton-classes/` but it didn't work – Harikrishnan Jul 18 '13 at 06:10
  • this sounds like a problem about passing data between view controllers more than anything else, take a look [at this answer](http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) it is very detailed and if it doesnt help, then as Valentin said in the comments, maybe a singleton solution will help you. – Fonix Jul 17 '13 at 15:13

0 Answers0