Search code examples
objective-csetterlvalue

Does "LValue" not mean what I think it means?


In the following code:

_imageView.hasHorizontalScroller = YES;
_imageView.hasVerticalScroller = YES;
_imageView.autohidesScrollers = YES;

NSLog(@"scrollbar? H %p V %p hide %p", 
      &(_imageView.hasHorizontalScroller), 
      &(_imageView.hasVerticalScroller),
      &(_imageView.autohidesScrollers));

I'm getting the error:

Controller.m:143: error: lvalue required as unary '&' operand
Controller.m:144: error: lvalue required as unary '&' operand
Controller.m:145: error: lvalue required as unary '&' operand

Notice that I am USING those variables as lvalues directly before the & lines...

How can it complain that a value isn't an lvalue right after I assign to it with no error? does this have to do with the magical getters/setters that objective C creates?

I think I need to explain some context to explain WHY I'm trying to get the address:

in my previous SO post, I showed the same code, printing %d and finding that after the assignments, the properties were still 0 for some reason. So, I figured I'd try to get the addresses of the properties to see where they're being stored and maybe I can figure out why I'm not successfully assigning to them, and then this happened.

I think that as people have mentioned, yeah, it's probably that when I do the assigment obj-c is secretly replacing that with a call to the setter (and then some other magic because in another SO post, someone else mentioned that

BOOL b = [_imageView setHasVerticleScroller: YES]

fails, but

BOOL b = _imageView.hasVerticalScroller = YES;

works fine.


Solution

  • _imageView.hasHorizontalScroller = YES; - in this line you access property in imageView - so you do not actually access value, but call setter method:

    [_imageView  setHasHorizontalScroller:YES]; // Equivalent of your code.
    

    In second example you also access property, but this time getter method gets called and returns BOOL. So as mipadi points you do not need to use & in that NSLog statement.

    I'd suggest to read docs about properties in obj-c.

    Edit: here you can find the discussion about why properties work in multiple assignment statements like you mentioned:

    BOOL b = _imageView.hasVerticalScroller = YES;