Reputation: 481
I'm new to Objective-C, and I can not understand what is the difference between the declaration of variables (firstString, secondString and thirdString) in MyClass.h:
@interface MyClass {
NSString *firstString;
}
@end
in MyClass.m:
@interface MyClass() {
NSString *secondString;
}
@end
@implementation MyClass
NSString *thirdString;
@end
I guess that the first and the second case is the same thing, but in what case it is better to use?
Thanks a lot!
Upvotes: 4
Views: 178
Reputation: 130102
There is no functional difference between the three, it's mainly visibility control.
The first one is declared in a public header of you class, that means that you want the programmers the know about the variable. If the access to this property is restricted (e.g. @private
), it should not appear in public header anymore and you should use the second or forth option.
The second is declared in the class continuation, meaning that it is needed only by the implementation.
The third one is a global variable, something you should use only in exceptional cases.
Missing another option
@implementation MyClass {
NSString *thirdString;
}
@end
(allowed by the latest Apple compilers) is the same as 2, without the need to create the class continuation.
Upvotes: 1
Reputation: 7687
firstString
is declared in the header, the file which is #import
ed by other classes. It is exposed to other classes and can therefore be accessed by subclasses and, since the symbol is available in the header file, it will be simpler for external objects to alter through key-value coding.
secondString
is declared in your implementation file. The ()
in @interface MyClass ()
signifies that this is a class extension. secondString
will not be exposed to external classes (though, as with everything in Objective-C, you cannot consider it to be truly private).
Upvotes: 3
Reputation:
The first and second variables will be instance variables, whereas the third one will be a file-scope global variable. Typically you should use instance variables and avoid using global variables.
Upvotes: 2