Re: error: invalid lvalue in assignment
Re: error: invalid lvalue in assignment
- Subject: Re: error: invalid lvalue in assignment
- From: Ken Thomases <email@hidden>
- Date: Mon, 25 Aug 2008 21:47:15 -0500
On Aug 25, 2008, at 6:25 PM, Don Arnel wrote:
I tried to modify the "position" property in another file after
creating an object but I get this error:
obj.position.x += 1.0;
(x error: invalid lvalue in assignment)
The above is equivalent to:
[obj postion].x += 1.0;
That isn't doing what you want. It's invoking the -position method
on the object, which returns a Vector2D struct. Note, that this
returned struct is not the same as the _position ivar of obj; it's a
copy of that. Although C++ has a notion of a reference as a type,
neither C nor Objective-C does. So, there is no way to return the
same struct. You could return the address of your struct, but that
would make for awkward usage.
The compiler complains because the returned struct (which is a copy
of obj's _position) is a temporary object. It doesn't have any
declared storage. It will be lost immediately after the statement
completes. So, assigning/modifying its members is just pointless.
Lastly, even if you could modify the x field of obj's _position ivar
in this way, it's a bad idea. It violates the encapsulation of the
myObject class. For example, what happens if some other aspect of
the object needs to be changed whenever the position changes? The
object isn't being informed when its internal state is changed, and
so it can't take any necessary action that might correspond with the
change.
I can assign the value without a problem:
float x = obj.position.x;
This is equivalent to:
float x = [obj position].x;
which again gets a copy of the struct that's in the _position ivar,
but then it just reads that copy's x field. Because it's just
reading, it's fine.
x += 1.0;
But then this is also a no-no:
obj.position.x = x;
Same problem as the first.
Cheers,
Ken
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden