In Objective C what scenario would I want to use [self setVariable:value]; instead of variable = value;
It seems as if doing a self set I’m saving myself few lines of code, but what other advantages are there? Additionally, when would I NOT want to do a self set?
EDIT:
I should clarify, that what I am referencing below is strictly in regards to variables that are properties. If a variable is just an ivar, then there is no difference between
self.variable = valueorvariable = value, other than the fact thatself.variable = valuewill not even compile if it is just an ivar, in that case you need to useself->variable = valueCalling
is the same as calling
This, however, is NOT the same as
The first two cases use the synthesized
setVariablemethod (or the one you defined yourself). The reason you would want to use this is to make sure you keep the proper retain count on your objects.For example, a simple property such as:
Gets an automatically generated set function that looks something like:
If you were to just call
elsewhere in your code, then
myStringis not retained properly, so ifotherStringgets deallocated, your pointer to that object is no longer valid.