Reputation: 103
I am very new to Objective-C programming, and I have a question that has always puzzled me: why do you have to declare your variables in the header file, like this?
@interface MyViewController : UIViewController
{
NSString *myString;
}
Why not just declare them here (in the .m file):
@implementation MyViewController
- (void)viewDidLoad
{
NSString *myString;
}
Upvotes: 0
Views: 76
Reputation: 16358
There are two different questions going on here.
To put it simply, the header file (.h) is a public gateway for everything else to see what your class is about without having to know anything about your implementation. Your header file should contain everything that you would want other classes to know about (i.e. public methods, properties).
You could easily declare things in the implementation file but then other classes would not know about them.
Secondly, in the example you provided you have put NSString *myString;
in the viewDidLoad method. This means that such a variable would be only available in the scope of that method. Nothing else would be able to access it.
Upvotes: 0
Reputation: 112857
The first declaration is a instance variable available to all instance methods. The second is local to the one method.
However it is possible to declare instance variables in the .m file:
@implementation MyViewController {
NSString *myString;
}
In fact this is the preferred way to declare instance variables that do not need to be exposed. Only declare things in the .h file that need to be available to other classes.
Upvotes: 4