I have a few questions:

  1. What is the difference between writing @synthesize var and @synthesize var = _var;

  2. How is ivar different from prop?

thank

  • MM has nothing to do with it, it's just different things. - AlexDenisov

2 answers 2

@synthesize var is the same as @synthesize var = var .

Defines a property var, using the var variable to store the value. (They call it ivar) For the case of @synthesize var = _var , it is used, of course, the instance variable _var.

Now what's the difference. When you declare a property, you actually implicitly define two functions: the getter (which returns the property value) and the setter (which sets). The simplest implementation of the getter and setter is to simply read from some variable and write to it. But they can also do more complicated things: retain / release, writing to the log, whatever. When you write @synthesize var = _var , you say that this variable itself will be called _var, in case you want to read it yourself.

Note that if you say self.var from the inside of the class, you get a call to property: you get, of course, the value that is written in ivar, but additionally there are things that are defined in the getter. If you use the var notation, you get exactly the variable, bypassing the getter. All clear?

Now see why property is needed. The fact is that for a public variable you cannot control its use. For example, you cannot open a variable only for reading. Or you cannot be convinced that everyone who uses a variable, correctly do retain. Therefore, a good style is to give access to variables through property, and to hide variables.

  • Thank you very much, but there was confusion - Dmitry99
  • @ Dmitry99: please! - VladD

1) _var "should" be private.
var is prop for _var
it (_var) should be specified explicitly when writing custom (setIvar:)
by default @synthesize var , let's say, equivalently @synthesize var = _var;

2) Wiki properties

  • It should not be private, it can even be public. - AlexDenisov
  • @ 1101_debian: this is why the word should have been bracketed. This practice is good. in order for it to be "at least public" is partly the merit of property - hash3r