The difference between variable declaration methods

I am new to Objective-C, and I canโ€™t understand what is the difference between declaring variables (firstString, secondString and thirdString) in MyClass.h:

@interface MyClass { NSString *firstString; } @end 

in MyClass.m:

 @interface MyClass() { NSString *secondString; } @end @implementation MyClass NSString *thirdString; @end 

I suppose the first and second case are the same thing, but in which case is it better to use?

Thanks a lot!

+4
source share
3 answers

There is no functional difference between the three; it is basically a visibility control.

  • The first is declared in the public header of your class, which means that you want programmers to know about this variable. If access to this property is restricted (for example, @private ), it should no longer appear in the open header, and you should use the second or fourth option.

  • The second is declared in the continuation of the class, which means that it is needed only for implementation.

  • The third is a global variable that you should use only in exceptional cases.

  • Missing another option

 @implementation MyClass { NSString *thirdString; } @end 

(allowed by the latest Apple compilers) is the same as 2, without the need to create a continuation of the class.

+1
source

firstString declared in the header, file #import ed by other classes. It is exposed to other classes and therefore may be accessible to subclasses and, since the symbol is available in the header file, it will be easier if external objects are changed through the encoding key value .

secondString declared in your implementation file. () in @interface MyClass () means it is an extension. secondString will not be exposed to external classes (although, like everything in Objective-C, you cannot consider it truly private).

+3
source

The first and second variables will be instance variables, while the third will be a global scope variable. Usually you should use instance variables and avoid using global variables.

+2
source

All Articles