Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: Different ways of declaring private variables. Any differences between them?

Tags:

objective-c

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.

like image 324
CodeHelp Avatar asked Dec 05 '22 09:12

CodeHelp


2 Answers

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.

like image 79
Binarian Avatar answered Jan 01 '23 09:01

Binarian


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.

like image 26
trojanfoe Avatar answered Jan 01 '23 08:01

trojanfoe