I need to access the value of a variable in ClassA.m after I load the view ClassB.m, but it seems as though when I switch the view from ClassA to ClassB, the variables from class A are destroyed. What is the best way to maintain this variable in ClassA? In Java, this would be rather easy, in the form of a static variable. However, I am not aware of such a concept in Objective-C. If you would recommend using an "extern" variable, I tried that, and that variable type also seemed to be destroyed after the view switch? Perhaps I am implementing incorrectly, but what are your thoughts? How do I maintain the value of a variable in the second view after the first view is dismissed?
Asked
Active
Viewed 149 times
3 Answers
2
You can create property in new viewcontroller and pass current viewcontroller's variable to new. see exp.
DetailsViewController *detailsviewcontroller = [[DetailsViewController alloc] initWithNibName:@"EventDetailsViewController" bundle:nil];
eventdetailsviewcontroller.event = localvar;
[self.navigationController pushViewController:detailsviewcontroller animated:YES];

Jasmin Mistry
- 1,459
- 1
- 18
- 23
1
Forget about static variables for now. The idea is that you want an object to keep reference of those variables regardless of which view is on. That's what the mediator pattern is for. Basically you want to have a controller of controllers (make it a singelton), and that controller can keep a reference to all the variables you want to keep around while views come and go.
This way you decouple your code, which translates to decreasing the dependency between potentially unrelated controllers and reducing glue code.
I gave a similar answer here as well.
-2
You can use static variable in Objective-C. This is an example in Test.m file
static NSMutableDictionary* single = nil;
@implementation Test
@end

CodeHelp
- 1,328
- 5
- 21
- 37