Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>(1) You're accessing it correctly.</p> <p>(2) In objective-c 2.0, the assignments have identical affect. </p> <p>Design wise, you would want to make:</p> <pre><code>-(void) setPosX:(int) inPosX andPosY:(int) inPosY; </code></pre> <p>...into a method of Position. This encapsulates both the data and the methods related to into one object. So you could have calls like:</p> <pre><code>coord = [[Position alloc] initWithX:inPosX andY:inPosY]; </code></pre> <p>or [coord setPosX:inPosX andPosY:inPosY];</p> <p>all much cleaner and easier to maintain.</p> <hr> <p>Edit O1</p> <blockquote> <p>Do I then call -(id)initWithX:andY: from the Rectangle object when I init it?</p> </blockquote> <p>That depends on your design. If the <code>coord</code> property is absolutely vital to the <code>Rectangle</code> instance, then you should call it when you initialize a <code>Rectangle</code> instance. You might even write an initializers for <code>Rectangle</code> that takes a position or x and y as input. eg:</p> <pre><code>-(id) initWithPosition:(Position *) aPos { self = [super init]; if (self) { NSLog(@"_init: %@", self); coord = aPos; // Released in dealloc (not shown) } return self; } </code></pre> <p>You should also write a connivence initializer for the Position class:</p> <pre><code>-(id) initWithX:(NSInteger) x andY:(NSInteger) y{ self=[super init]; self.posX=x; self.posY=y; return self; } </code></pre> <p>You would then call like:</p> <pre><code>Position *aPos=[[Position alloc] initWithX:100 andY:50]; Rectangle *aRec=[[Rectangle alloc] initWithPosition:aPos]; </code></pre> <p>Or you could write another combination initializer for Rectangle:</p> <pre><code>-(id) initWithXCoordinate:(NSInteger) x andYCoordinate:(NSInteger) y{ self=[super init]; Position *aPos=[[Position alloc] initWithX:x andY:y]; self.coord=aPos; return self; } </code></pre> <p>and call it like:</p> <pre><code>Rectangle *aRec=[[Rectangle alloc] initWithXCoordinate:100 andYCoordinate:50]; </code></pre> <p>These are rough examples but you get the idea. Objective-c gives you a lot of flexibility in setting up initializer so you can create any initializers you find convenient. </p> <p>You do generally want to avoid using actual functions instead of methods inside classes. </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