I have defined an object with a CGPoint ivar and associated property as follows...
@interface Sprite : NSObject {
CGRect boundingBox;
}
@property(assign) CGRect boundingBox;
When I use an instance of the Sprite class an开发者_JAVA百科d try and update the boundingBox struct as follows...
self.boundingBox.origin.x = minX;
I receive a compile time error stating...
Lvalue required as left operand of assignment
Am I correct in saying that self.boundingBox will return a C struct, which isn't actually the struct held by the Sprite object but rather a copy of it? Therefore when the assignment of a new value for x fails because the struct is only a temporary copy?
If this is the case will the following code work correctly (and is it the correct way to achieve what I want)?
CGRect newBoundingBox = self.boundingBox;
newBoundingBox.origin.x = self.boundingBox.origin.x;
self.boundingBox = newBoundingBox;
Remember that properties are just syntax aliases to setter and getter methods. This:
self.boundingBox = newBox;
Is equivalent to this:
[self setBoundingBox:newBox];
The reason you can't do this:
self.boundingBox.origin.x = minX;
Is because there's no way to call setBoundingBox:
but only ask it to change origin.x
, and there are no individual setter methods available for the individual parts of the struct. The example at the end of your question is the only way to achieve what you're trying to via properties.
You can of cause forget about properties and do this:
boundingBox.origin.x = minX
That writes directly to the current objects boundingBox
instance variable (assuming one exists), but bypasses the setter method, which may be undesirable.
EDITED ANSWER: My original comment about not being able to edit any CGRect was wrong; the actual problem with that first line of code comes from the fact that you're using self.boundingBox
to access the CGRect
. Your second code will work great, along with the block I had in my original answer:
To properly change values inside boundingBox
, you'll need to use apple's CGRectMake
function, like so:
CGRect r = self.boundingBox;
self.boundingBox = CGRectMake(minX, r.y, r.width, r.height);
For a nice explanation of why the self.
notation is a problem with structs, check out the answers to this question. Hope this helps!
精彩评论