Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to define private variables in Objective-C

Tags:

objective-c

I want to define private instance variables in MyClass.m file. It seems to me there are two ways to do it:

  1. use class extension

    @interface HelloViewController () {      int value; } 
  2. define in @implementation section

    @implementation HelloViewController {     int value; } 

Which is better?

I think recent Apple's coding style is to use class extension?

e.g. MasterViewController.m generated by 'Master-Detail Application Template'

@interface MasterViewController () {     NSMutableArray *_objects; } @end 
like image 388
Makoto Otsu Avatar asked Nov 23 '12 16:11

Makoto Otsu


People also ask

How do you define a private variable?

In general, private variables are those variables that can be visible and accessible only within the class they belong to and not outside the class or any other class. These variables are used to access the values whenever the program runs that is used to keep the data hidden from other classes.

Can we access private variable through object?

We cannot access a private variable of a class from an object, which is created outside the class, but it is possible to access when the same object is created inside the class, itself.

How do you define a private variable in a classroom?

Class variables that are declared as private can not be referred to from other classes, they are only visible within their own class. It is considered better programming practice to use private rather than public class variables, and you should aim to do this in the remainder of the course.

When should you use private variables?

Making a variable private "protects" its value when the code runs. At this level, we are not concerned with protecting it from other programmers changing the code itself. The point of so-called "data hiding" is to keep internal data hidden from other classes which use the class.


1 Answers

The "Modern Objective-C" way to do this is to declare them in your implementation block, like this:

@implementation ClassName {     int privateInteger;     MyObject *privateObject; }  // method implementations etc...  @end 

See this earlier post of me with more details.

like image 109
DrummerB Avatar answered Oct 14 '22 15:10

DrummerB