If some one can brief on declaring instance variable inside .h file inside @interface braces and in .m file @interface braces. like this below
@interface ViewController : UIViewController { NSString *str ; }
@interface ViewController () { NSString *anotherStr ; }
Thx
There's even a third place where you can define instance variables: at the implementation statement:
@implementation ViewController { NSString *yetAnotherString; }
AFAIK, in the olden times you could only define the instance variables in the main interface. The other two places were added later. You can also mix them (as long as they have different names).
The advantage of defining the variables at @implementation
and also the class extensions @interface ViewController ()
level (when done inside an .m
file) is that you can hide implementation details from users of your API. In other words, if someone reads the .h
file (s)he doesn't know about the variables. This makes the visible API cleaner and is also a concept called "information hiding" which is quite important in object oriented programming: don't expose too much implementation details so you can change the implementation without breaking code using the class.
Note that you can also define IBOutlet
variables at all three levels and Interface Builder will detect and use them!
So when you're deciding where to define the variable you can simply ask yourself: Do other people need to see the variable when they see the .h
file? IMHO this is only true when you need/want to make a variable @public
. For all other cases, you can define them at the class extension or implementation level to make the API cleaner.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments