Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Objective-C, do we have to use self.var or just var to reference a property of self?

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?

like image 894
nonopolarity Avatar asked Dec 21 '22 16:12

nonopolarity


2 Answers

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:

  • except in init, dealloc and the view accessors (if you custom write them), always use self.view.
  • In those methods, you should refer to it as _view.
  • If you are writing for the latest Xcode, do not include @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.
like image 71
Rob Napier Avatar answered Apr 26 '23 05:04

Rob Napier


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.)

like image 27
Jesse Rusak Avatar answered Apr 26 '23 04:04

Jesse Rusak