0

So i ran into a weird problem when working with array that inside a method, if i went to print the contents of a array by going

NSLog("Number of items:%@ , _array.count)

I would get 0 but calling

NSLog("Number of items:%@, self.array.count)

I would get the correct number. The array would have been declared at the top, using @property and I would have stored items into the array earlier in the method before calling NSLog. I've always understood that "self" is the same as "_", am i wrong, are there minor details that I am missing.

Thanks

edit----------------------

the line of code was

[_currentSelectedRoutes setObject:newMapRoute forKey:route.shortName]

and the code was set for lazy instantiation

Anthony Taylor
  • 3,073
  • 3
  • 21
  • 30

1 Answers1

2

Yes, you are wrong. _var is not the same as self.var

When you declare a property like

@property NSString *lastname;

the compiler will create an instance variable called _lastname.

Then the compiler creates two methods:

- (NSString *) lastname;
- (void) setLastname:(NSString *) lastname;

These methods are doing nothing else by default than setting and returning _lastname. They are there that methods in other classes can access the contents.

If another class would want to access the value of lastname it would be done like this:

person.lastname

The compiler compiles that like this:

[person lastname]

You see? That's the reason for this methods and why properties where introduced. If you do:

self.lastname

This will also call the getter method. But

_lastname

will directly access the instance variable. That's also the reason for you can set and a readonly property by using the underlying ivar.

It can always be that there's a custom g/setter. In your case for instance the getter probably returns another (or modified) array.

idmean
  • 14,540
  • 9
  • 54
  • 83
  • 1
    Also, one important case of there being a "custom" accessor is when a subclass overrides to extend the property or do other work (like when the subclass wants to know when the property has been changed to trigger some other logic). That's an important reason to use the accessors (including via dot syntax) rather than directly accessing the instance variable. – Ken Thomases Sep 03 '14 at 19:18