Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As a starting point, you should set up your <code>.h</code> to something more like this:</p> <pre><code>@interface Circle : NSObject @property double radius; @property (readonly) double area; @property (readonly) double diameter; @property (readonly) double circumference; @property (readonly) double pi; -(id)initWithRadius:(double)r; +(instancetype)circleWithRadius:(double)r; @end </code></pre> <p>This will set up a <code>setter</code> and <code>getter</code> for <code>radius</code> as well as <code>getters</code> for <code>area</code>, <code>diameter</code>, and <code>circumference</code>. It also sets up an <code>init</code> and <code>factory</code> method for your <code>circle</code> which takes a double for the radius.</p> <p>I will come back and edit in some modifications you need to make to your <code>.m</code> as well as your <code>main</code> file in order to make this work. As a note, at a minimum we'll override the <code>getters</code> for the 3 <code>readonly</code> properties. This will prevent the compiler from creating <code>ivars</code> (instance variables) for these properties (because we can just calculate and return the number we calculation when we call it).</p> <p>In your <code>.m</code>:</p> <pre><code>#import Circle.h @implementation Circle -(id)initWithRadius:(double)r { self = [super init]; if(self) { self.radius = r; } return self; } +(instancetype)circleWithRadius:(double)r { return [[Circle alloc] initWithRadius:r]; } -(void)setRadius:(double)r //This method is automatically created by @property { //include any verification logic (make sure r&gt;0 etc), then... self.radius = r; } //we don't really need to override the radius getter -(double)pi { return 3.14159; //or however much accuracy you want } -(double)area { return (self.pi * self.radius * self.radius); } -(double)diameter { return (2.0 * self.radius); } -(double)circumference { return (self.diameter * self.pi); } </code></pre> <p>In <code>main</code>, you use this <code>Circle</code> class in just the same way you use any other object in Objective-C (think about <code>NSString</code>, <code>NSArray</code>, etc).</p> <pre><code>int main(int argc, const char * argv[]) { @autoreleasepool { double radius; NSLog(@"Enter the circles radius:"); scanf ("%lf", &amp;radius); Circle *myCircle = [Circle circleWithRadius:radius]; //the factory method we set up NSLog(@"myCircle radius: %lf", myCircle.radius); NSLog(@"myCircle area: %lf", myCircle.area); NSLog(@"myCircle diameter: %lf", myCircle.diameter); NSLog(@"myCircle circumference: %lf", myCircle.circumference); } return 0; } </code></pre>
 

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