0

I have declared in the .h class

@property (nonatomic, readonly) SomeClass *sup;

In the init in the .m class, I can say

_sup = [[SomeClass alloc] init];

but not

self.sup = [[SomeClass alloc] init];

This is because it's read-only. What's the difference?

Bryan Chen
  • 45,816
  • 18
  • 112
  • 143
FoxMcWeezer
  • 113
  • 1
  • 7
  • Along with plenty of others: [Difference between self and normal variable](http://stackoverflow.com/q/536388/), [Properties and accessors](http://stackoverflow.com/q/6085080/), [Ivar property, access via self?](http://stackoverflow.com/q/4088801/), [When to access properties with self](http://stackoverflow.com/q/4271657/), [What is the (style) difference between “self.foo” and “foo” when using synthesized getters?](http://stackoverflow.com/q/3494157/), [Difference between calling self.var vs var](http://stackoverflow.com/q/4627646), [&c.](http://stackoverflow.com/search?q=%5Bobjc%5D+self.ivar) – jscs May 28 '14 at 05:33
  • This is not done simply because the public interface of `sup` was `readonly` (because you could/would define a private non-`readonly` interface in the private class extension, thus letting you use setter privately while keeping object `readonly` for external purposes). In reality, the reason you use `_sup` has less to do with the lack of a setter than it does with the fact that it's discouraged to use accessor methods within `init` method. Even if `sup` was originally defined as non-`readonly`, you still would not use `self.sup = ...` in init. – Rob May 28 '14 at 05:38
  • See [Don’t Use Accessor Methods in Initializer Methods and dealloc](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html#//apple_ref/doc/uid/TP40004447-SW6) in the _Practical Memory Management_ section of the _Advanced Memory Management Programming Guide._ – Rob May 28 '14 at 05:39
  • 1
    In the spirit of Josh's attempt to enumerate existing duplicate questions, I might direct you, instead, to [Best practice on using @property ivars](http://stackoverflow.com/questions/12752946/best-practice-on-using-property-ivars) or [What is the correct way of init iVar variables in presence of ARC](http://stackoverflow.com/questions/12035149/what-is-the-correct-way-of-init-ivar-variables-in-presence-of-arc/) or [iOS : Other alternative to instance variable?](http://stackoverflow.com/questions/12529833/ios-other-alternative-to-instance-variable/). – Rob May 28 '14 at 05:54

2 Answers2

3

When you are using _sup, you are accessing the variable behind that property directly. When you say self.sup you are accessing it through the setter method, which you cannot do, since it is readonly. Read more about properties here.

Levi
  • 7,313
  • 2
  • 32
  • 44
0

Readonly means setter method is not created. So, once you are access it through self.sup, it means you are calling a method which is not created.

_sup is a variable access only.

Samkit Jain
  • 2,523
  • 16
  • 33