Reputation: 1328
I have thought of different ways of declaring private variables. I want to know whether there are any differences between them.
First way:
//In .h file
@interface DataExtract : NSObject
{
@private
double test;
}
Second way:
//In .m file. test is not declared in .h file
static double test;
Third way:
//In .m file. test is not declared in .h file
double test;
Any help would be much appreciated. Thank you.
Upvotes: 4
Views: 3587
Reputation: 2751
Is there a reason you want to use just an instance variable, instead of a property?
You can declare a private property like so:
// Private Interface in .m file
@interface DataExtract()
@property (nonatomic) double test;
@end
Edit: If you do want to use a private ivar, instead of a property, you could do it like so:
// Private Interface in .m file
@interface DataExtract() {
double test;
}
@end
Upvotes: 1
Reputation: 12446
All of them are not a good solution if you want an ivar. I would even tend to only use properties with autogenerated ivars in an class extension in the implementation file only one line (@synthesize is automatically generated in Objective-C 3.0).
First way:
Yes this is an ivar, but you shouldn't declare it in the header file, if you declare it @private, then use the @implementation {...} block. In the implementation block you don't need to declare it @private, because it defaults to @protected, but in the implementation block it is not visible for subclasses
Second way:
That is a variable only visible in the translation unit, here the .m file itself. It is not global for the whole app. The value is persistent for every instance of your class, so it is no ivar (instance variable).
Third way:
That is also no ivar, it is a variable which defaults to extern, because you did not write static. That means it is in the global symbol table and can be used in other translation units /files if they #import/#include the .m file.
Upvotes: 5
Reputation: 994
You can declare a private @interface in the .m file.
//DataExtract.m
@interface DataExtract ()
//your variables
@end
@implementation DataExtract
@end
For more info you can go here
Upvotes: 5
Reputation: 122391
Your second and third examples are not instance variables, but global variables (with differing scope) and the same value will be shared across the entire process.
Upvotes: 5