In Objective-C, can we put instance variables in the @implementation section?

Possible duplicate:
Is this a new way to define private instance variables in Objective-C?

I always put the instance variables in the .h interface file, but just saw some kind of code doing this:

 @implementation Fraction { int numerator; int denominator; } 

which should move instance variables to the implementation side. It also works, but since when can we do this (or can we always do this with Objective-C), and I believe this is better, because the used instance variables are not part of the interface.

+6
source share
2 answers

Yes, this is the preferred way, and in the same way, we use the class extension to define private properties to hide sharing.

Sort of -

 //Class Extension for private properties and methods @interface Fraction () @property (nonatomic, assign) int numerator; @end // Define private instance variable @implementation Fraction { int numerator; int denominator; } // Synthesize properties for generation of getter and setter @synthesize numerator = _numerator; @end 
+2
source

This feature was already in Objective-C. The main purpose of this feature is data hiding or data privacy.

If you want to use some private variables that cannot be accessed outside the class, you can go with a category, in particular a .m file.

Even in Xcode 4.3.2, when you create a new class, then the default .m file contains one category by default. (just before implementation).

 ViewController.m **@interface ViewController () @end** @implementation ViewController ....... 

In this interface you can declare your private members. And you can use them simply with [self variableName] in the entire .m file.

Similarly, you can declare your private methods in the same category.

So, your instance object created outside the class file cannot read these variables and methods.

Hope this is what you are looking for.

Enjoy the coding :)

0
source

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


All Articles