If I add a property to the ViewController
@property (strong, atomic) UIView *smallBox;
and synthesize it in the .m
file, the variable can actually be referenced just by smallBox
inside of any instance methods.
But then, self.view
cannot be replaced by view
, even though view
is defined as a property of UIViewController too. Why the difference and what is the rule?
self.view
and view
/_view
are not the same thing. Depending on how you create your instance variables, view
or _view
refer to the actual object instance variable. It is dangerous to access this directly, and you should only do so in init
, dealloc
or in accessors. Everywhere else, you should use self.view
.
self.view
is exactly the same as [self view]
, which passes the message "view" to the object "self" an returns the result. By default, when an object receives a message, it executes the method with that name, and the default implementation of view
will return the value of the related instance variable (either view
or _view
).
In older versions of Xcode, @synthesize view
would create an instance variable called view
. In the latest versions of Xcode, declaring a property view
will will automatically create an instance variable called _view
in many cases, even without @synthesize
. This change makes it easier to notice when you are accessing the ivar directly.
In short:
init
, dealloc
and the view
accessors (if you custom write them), always use self.view
._view
.@synthesize
at all. If you are writing for a slightly older Xcode, use @synthesize view=_view;
self.view
does not mean "the value of the instance variable." It means "the result of passing the message 'view'" which is generally implemented as returning the instance variable.You can't access the view
member directly because it's declared as @package
visibility in UIViewController
. This prevents your code from accessing it. (Normally, you wouldn't want to access instance variables of your superclasses directly anyway.)
For your class's own properties, you can access the instance variable directly, but you need to be aware of the memory management implications of this. (As well, as Rob points out, as any other behaviours you're side-stepping by avoiding the accessor.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With