Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy can't I assign variable value directly?
    text
    copied!<p>I am new Objective C. I am trying to understand and workout problems from Stephen Kochan's Programming in objective c 2.0. This problem is from chapter 8. </p> <p>What I don't understand is: why can't I assign variable values directly when I can get them. </p> <p>For example: </p> <p>This does not give me a error or warning. But it also does not set the value of X and Y. </p> <pre><code>go.origin.x = 300; go.origin.y = 100; </code></pre> <p>But, this works fine and gives me the intended result:</p> <pre><code>NSLog (@"print %i, %i", go.origin.x, go.origin.y); </code></pre> <p>Here is my XYPoint.h</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @interface XYPoint : NSObject { int _x; int _y; } @property int x; @property int y; @end </code></pre> <p>XYPoint.m</p> <pre><code>#import "XYPoint.h" @implementation XYPoint @synthesize x = _x; @synthesize y = _y; @end </code></pre> <p>GraphicObject.h</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; #import "XYPoint.h" @interface GraphicObject : NSObject { XYPoint *_origin; } @property (nonatomic, retain) XYPoint *origin; -(void) setOrigin : (XYPoint *) pt; @end </code></pre> <p>GraphicObject.m</p> <pre><code>#import "GraphicObject.h" @implementation GraphicObject @synthesize origin = _origin; -(void) setOrigin : (XYPoint *) pt { _origin = [[XYPoint alloc] init]; _origin = pt; //_origin.x = pt.x; //_origin.y = pt.y; } @end </code></pre> <p>Also if don't want my origin.x and origin.y to be changed when I change my xypoint x and y, why do I have to do this:</p> <pre><code>_origin.x = pt.x; _origin.y = pt.y; </code></pre> <p>and why not just:</p> <pre><code>_origin = pt; </code></pre> <p>For example in the <strong>main</strong> file:</p> <pre><code>XYPoint *myPoint = [[XYPoint alloc] init]; go.origin = myPoint; myPoint.x = 250; myPoint.y = 50; NSLog(@"Origin values %i, %i", go.origin.x, go.origin.y); myPoint.x = 100; myPoint.y = 10; NSLog(@"Origin values %i, %i", go.origin.x, go.origin.y); </code></pre> <p>I understand that the values of origin don't change. But do I have to, in the setOrigin: method, assign it in this way:</p> <pre><code>_origin.x = pt.x </code></pre> <p>and not like this:</p> <pre><code>_origin = pt; </code></pre> <p>Thanks everyone. I know this is a long question. I really tried to understand and also looked in many places but I don't even know what to search for. What do you call this kind of assignment? </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload