Thursday, May 21, 2009

iPhone dev Stupidity 4





* Should there be a self for an ivar?

Beginning iPhone Development, Chap 7, page 166
Q: Could we omit that self in self.stateZips?

A: If it's omitted, the assignment is normal pointer alignment - the synthesized getter/setter will not be invoked here.

That is: the (retain, nonautomic)  will not applicable. After the [dict release], stateZips will also be gone.

-----

more explanation from Stack Overflow :

The assumption is that you shouldn't (usually) be accessing instance variables directly. Mostly this is because doing so circumvents the Key-Value Observing machinery in Cocoa. Rather, the expectation is that you'll access and mutate properties via getter/setter methods. 
...
The only time you should be accessing instance variables directly is in -init and -dealloc methods.

The reason the ivar should be used directly in these cases is beacuse the getter/setter may have side effects that depend on a fully initialized instance, thus making them dangerous in -init and -deallocwhere the state of the object is fully initialized. In all other cases, you should be using self.ivar (or[self ivar] and [self setIvar:newValue]).

-----

So the bare assignment stateZips = dict is the same with self->stateZips = dict - both walk around the generated getter/setter.

Q: How about the getter?
A: It's safe if you don't do extra works in the getter.

No comments: