views:

38

answers:

1

In my .h file I have a NSMutableArray *locationsArray defined with a property as follows

@property (nonatomic, retain) NSMutableArray *locationsArray

In my .m file I was displaying a table view, this loaded fine until I tried to roll-up at which point I it crashed with bad access. This was due to the locationsArray not being retained.

This line of code fixed my problem in the .m

locationsArray = [[Locations loadLocations] retain] (#1)

This line of code also fixed the same problem

self.locationsArray = Locations.loadLocations (#2)

I have a couple of questions I need clarification on

  1. is this the correct way to set this value, should I be doing an alloc init, alloc initwithArray?
  2. Comming from a java world I understand self is this, or at least I thought I did...What is different in objective C that the locationsArray without the self is not being retained without me adding the retain.

Obviously I got it working but it took as while and am still a little confused as to why. any help would be appreciated.

A: 
  1. Yes, if you set the instance variable (locationsArray) directly, you need to retain the value to keep it. You can either do that as you've done, or alloc/init it directly, which also means that you have a retain ownership of it.

  2. self is indeed equivalent to this in other OO languages. But there's a semantic difference in Obj-C between referring to an ivar "naked" like in your first example, and referring to it as self.locationsArray in the second. The former behaves how you'd imagine, but the latter is actually a syntactic shortcut for [self setLocationsArray: ... ] which does the retain automatically for you, because you've marked the property as being retain.

This last point is really subtle, and (to my view) not expected or obvious behavior. If you're still fuzzy on it, go back to the Apple docs. Really important to get this.

quixoto
To avoid the risk of this problem is this why lots of examples define the ivars with an underscore character and the property without the underscore?
jimsis
That's one reason people do that, yes. The general reason for scope marking like that is so that (a) when you're reading code, you can see at a glance inside a function what is a local var and what is an ivar, and (b) for convenience when a method (often a setter) takes a param of the same name, you don't have to write the silly `theString` or `anEvent` to avoid shadowing the ivar in scope.For what it's worth I dislike this getter/setter dot notation in Obj-C 2.0; I don't use it myself because I find it more confusing than helpful. YMMV.
quixoto