Xcode from scratch for scaredy cats: Sharing variables between methods in the same class

Note: If this is the first post in the series you have read, you'll first need to follow steps 1-5 in this blogpost to create the Xcode Project and also read this post on the insertion of code in an iOS app.

We can set an instance variable and use it within a method. For example if we created a New Project of the type Single View Application called Variable with a class prefix Variable, then in the VariableViewController.m file we could write
-(void)viewDidLoad
{
  [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.
    NSString *prop = @"hello";
    NSLog(@"%@", prop); 
}
This would work fine and the app would return the expected result (the word "hello" displayed in the console, which pops opens at the foot of your Xcode window when the Simulator is running). But suppose we want to set the value of the NSString in viewDidLoad but then read this value out in another method, for example when the device is rotated.

If we cut and paste the line:
NSLog(@"%@", prop);
from viewDidLoad and insert it into the following method:
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    NSLog(@"%@", prop);
}
this will cause the compiler to complain and you will receive warnings. This is because the didRotateFromInterfaceOrientation method has never heard of the variable "prop", it isn't visible to it.

How do we solve this? It is very simple. We just need one line of code before the @implementation section in the VariableViewController.m file, which is:
NSString *prop;
So the beginning of our file would look like this:
#import "VariableViewController.h"

NSString *prop;

@implementation VariableViewController

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

-(void)viewDidLoad
{
  [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.
    prop = @"hello"; // I've removed NSString * because it is no longer necessary, since the class of this instance variable has already been declared
}

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    NSLog(@"%@", prop);
}
...
@end
Now when the device is rotated in the simulator (cmd + arrow key left or right) the app will perform once again as expected, i.e. every time the device is rotated the console will display the "hello" message. 

This sharing of information between methods opens the door on a whole range of opportunities in your app, and you'll find detailed guidance on this in Apple's developer documentation here under the subheading 'Variables and Class Objects'.

Comments