12

In an .h file, what is the difference between:

@interface ViewController : UIViewController
@property (strong, nonatomic) UIView* myView;

And

@interface ViewController : UIViewController{
    UIView* myView;
}
Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
Chris G.
  • 23,930
  • 48
  • 177
  • 302
  • 1
    don't use strong for **myView** it will create a retain cycle go for [reference here](https://stackoverflow.com/a/11013715/3030400) – Muhammad Waqas Jan 04 '18 at 06:37

2 Answers2

17

The first one is the declaration of a property, whereas the second is only a ivar. A property is the automatic declaration of a getter and a setter for an ivar, but if there is not ivar (like in your first example) the property will create the ivar too.

iSofTom
  • 1,718
  • 11
  • 15
6

The main difference is that a @property is visible to other objects, and can be accessed by these using an instance of your class.

You can use @synthesize in your implementation file to automate definition de getter setter functions in your implementation.

Updated (following @Graham Lee's suggestion)

According to the visibility specifier for your instance variable (@protected / @private / @public) , the ivar can be used in your implementation file, subclasses or other classes. The implicit value is @protected, so in your example it will be visible to your implementation file and subclasses.

adig
  • 4,009
  • 1
  • 23
  • 23
  • 3
    instance variables with no visibility modifiers - like the one in this question - are implicitly `@protected`. Far from not being accessible from other objects, they can be used in any subclass of the class where they're declared. –  Oct 16 '12 at 12:22