Normally i’ve been passing variable around in init methods, but I can’t do that this time because I have a var in one ViewController class displayed using a tab bar and I need access to it from a different ViewController class when a different tab bar is pressed. My understanding was that you can access vars using @property but it’s now working so I’m doing something wrong. Here is what I have:
Class 1 Header file
@interface DailyViewController : UIViewController <UIActionSheetDelegate> {
NSDate *today;
}
@property (readwrite, nonatomic, retain) NSDate *today;
Class 2 implementation file:
- (void)viewWillAppear:(BOOL)animated{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterLongStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
DailyViewController *otherClass = [[DailyViewController alloc] init];
NSString* todayString = [formatter stringFromDate:otherClass.today];
r_todayLabel.text = todayString;
[otherClass release];
[formatter release];
}
You need to retrieve the DailyViewController* object from your AppDelegate (or wherever it is stored), and retrieve the date from it.
You are creating a new DailyViewController* object, not initializing it with its date, and then accessing its date field (which will be nil by default).
Something like
However all that is violating lots of rules of good programming.
Firstly, you should be aiming for MVC (Model View Controller), so your “today” date should be stored in your model. Then both classes could access today from the model rather than from one view’s controller and then there would be no need for class 2 to access the DailyViewController at all and so no need to store a reference to it in the AppDelegate, which is a bad idea since it has nothing to do with delegation for the UIApplication and is really just a global variable in disguise.