Reputation: 150956
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?
Upvotes: 4
Views: 940
Reputation: 57168
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.)
Upvotes: 1
Reputation: 299265
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.Upvotes: 10
Reputation: 912
Apple defined properties usually contain an underscore before their name, so when you use self.view
, it is actually getting the instance variable _view
from the object. You cannot use _view
in code, as it will cause a linker error on compiling, but Xcode will still highlight it for you. Another way of accessing the instance variable for self.view
is by self->_view
, but again, this causes a linker error. The reason for these linker errors is because the compiled libraries do not contain the symbols for _view
; even if its declaration can be found in UIViewController.h
.
Upvotes: 0