2

Ok, I am confused! I used to use -> whenever I accessed my instance objects, but now I see that after I set them in my application:didFinishLaunching like this:

self->counter = [NSNumber numberWithFloat:0.0f];

Down the road I got thrown out with an Exception, checked my debugger and saw that counter was pointing to a <non objective c object>

I changed the line to :

self.counter = [NSNumber numberWithFloat:0.0f];

And now I see in the debugger that I have yes another variable.

So, what is happening here?

Machavity
  • 30,841
  • 27
  • 92
  • 100
Ted
  • 3,805
  • 14
  • 56
  • 98

2 Answers2

3

self->counter = [NSNumber numberWithFloat:0.0f]; uses direct access to an ivar. With self, it is equal to counter = [NSNumber numberWithFloat:0.0f]; where counter is an ivar. That is to say self-> is a redundant scope qualification within an instance method.

self.counter = [NSNumber numberWithFloat:0.0f]; is syntactic sugar for [self setCounter:[NSNumber numberWithFloat:0.0f]];. Specifically, the declaration dynamically messages the object's setter for counter. Although there are exceptions, you should favor using the accessor when not in a partially constructed/destructed state.

Community
  • 1
  • 1
justin
  • 104,054
  • 14
  • 179
  • 226
  • 1
    To add to this correct answer, the form `self->counter` is not only redundant in an instance method scope, it throws a warning (or error) outside that scope, unless the ivar is marked (bizarrely...) `@public` – FluffulousChimp Nov 20 '12 at 11:14
  • @NSBum Right +1, although access is inconsistent and complex in ObjC. If you are writing for newer ABIs, then access is checked correctly. Older ABIs or compilers, then may instead emit a warning. It's `@protected` by default if declared in an `@interface` and `@private` by default when declared in an `@implementation` block. clang also permits access to privates in an `@implementation` body (e.g. if using a static function) -- as expected, it is an error outside the `@implementation` body O_O – justin Nov 20 '12 at 11:23
2

You're asking about the difference between iVars and properties. There's already a great answer on this question here.

Community
  • 1
  • 1
Rawkode
  • 21,990
  • 5
  • 38
  • 45