Objective-C: Various ways to declare private variables. Any differences between the two?

I was thinking of different ways to declare private variables. I want to know if there are differences between them.
First way:

//In .h file @interface DataExtract : NSObject { @private double test; } 

The second way:

 //In .m file. test is not declared in .h file static double test; 

The third way:

 //In .m file. test is not declared in .h file double test; 

Any help would be greatly appreciated. Thanks.

+4
source share
4 answers

All of them are not a good solution if you need Ivar. I would even use only properties with auto-generated ivars in the class extension in the implementation file in only one line (@synthesize is automatically generated in Objective-C 3.0).

First way:

Yes, it is ivar, but you should not declare it in the header file if you declare it @private, and then use the @implementation block {...}. In the implementation block, you do not need to declare it @private, because @protected is used by default, but in the implementation block it is not displayed for subclasses

The second way:

This is a variable visible only in the translation block, here the .m file itself. This is not global for the entire application. A value is stored for each instance of your class, so this is not ivar (instance variable).

The third way:

It is also not ivar, it is a variable that uses extern by default because you are not writing static. This means that it is in the global symbol table and can be used in other translation units / files if they # import / # include the .m file.

+5
source

You can declare a private @interface in the .m file.

 //DataExtract.m @interface DataExtract () //your variables @end @implementation DataExtract @end 

For more information you can go here.

+5
source

The second and third examples are not instance variables, but global variables (with different scope) and the same value will be shared throughout the process.

+5
source

Is there a reason you want to use only an instance variable instead of a property?

You can declare a private property as follows:

 // Private Interface in .m file @interface DataExtract() @property (nonatomic) double test; @end 

Edit: If you want to use a private ivar, instead of a property, you can do it like this:

 // Private Interface in .m file @interface DataExtract() { double test; } @end 
+1
source

Source: https://habr.com/ru/post/1500878/


All Articles