Is there a modern Objective-C convention to not have any Ivars that are not properties?

Possible duplicate:
iOS: should every iVar be property?

I just read a book that says that the modern convention is not to declare any ivars in your .h file between curly braces and to do all the properties instead.

I want to make sure that this is true even in trivial cases. I am making a class where there is a BOOL named β€œrecord” which says that the device is currently recording video. This is not what other classes need, but my slope is to simply put it as BOOL in the header and then access it in the .m file in two places where it is needed.

However, I also want to do everything right, right. But I do not understand why I am making this public property?

+4
source share
5 answers

What you are reading is wrong, simple and simple.

The modern convention is to skip ivars when there is an appropriate property that can synthesize them. In addition, with the latest versions of LLVM, you can transfer your ivars to your implementation file (as @DrummerB already mentioned), so there is no ivars in the header. This is considered good practice because it does not expose the inner workings of the class.

But you do not have Ivars in general and property for everything that was Ivar? No, not normal Objective-C.

+8
source

Your book is right (and wrong). Do not declare ivars in your headers anymore. This is only supported for compatibility reasons. But also do not declare properties for private variables.

If you want, declare a private ivar that other classes should not use, declare them in the implementation file:

// MyClass.m @implementation { BOOL recording; } // methods @end 
+5
source

I recommend not using ivar at all. Instead, you can create a class extension in which you will declare properties that should be hidden:

 @interface MyClass () @property (nonatomic, assign) BOOL recording; @end 
+2
source

You can use something like

 @interface G4AppDelegate () @property (nonatomic, assign) BOOL recording; @end 

Make an "internal" property.

Or how other response states use iVar in your implementation

+1
source

Some books explain that you should only use getter and setter to access your ivar, even if they are private. This is a little too psychotic for me.

Before clang, you need to create a category on the class and use a synthesizer to make ur ivar private. eg:

 @interface AppDelegate () @property(nonatomic, assign)int aValue; @end 

// + @implement AppDelegate // @synthetise aValue;

which can be annoying since someday you will need a simple ivar, without any getter / setter control. And add code that is not necessary.

Now with clang you can put ur ivar directly into the implementation file, similar to this in ur code:

 @interface AppDelegate (){ int _aValue; } @end 

And hide the private ivar from the header area. Please note: u cannot compile this with gcc.

0
source

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


All Articles