Joe Million
Joe Million

Reputation: 147

Objective-C Description not behaving as I would expect.

I'm trying to build a good triangle class, seeing I use them a lot. I decided to modify my class so that the user can set a bool, to choose to use degrees rather than radians. Every thing still seems to work as it should, except it's description, interestingly:

    IMTriangle *tri = [[IMTriangle alloc]init];
    tri.shouldUseDegrees = YES;
    tri.SideA = 3;
    tri.SideB = 4;
    tri.SideC = 5;

    [tri solve];
    NSLog(@"tri %@", tri);
    double A = tri.angleA;
    double B = tri.angleB;
    double C = tri.angleC;
    NSLog(@"A = %f  B = %f  C = %f",A,B,C);
    NSLog(@"tri  %@",tri);

Gives me this

tri a=3.0000 b=4.0000 c=5.0000 A=0.6435 B=0.9273 C=1.5708 perimeter=6.0000 area=12.0000 height=4.0000 shouldUseDegrees 1
A = 36.869897  B = 53.130098  C = 90.000004
tri  a=3.0000 b=4.0000 c=5.0000 A=36.8699 B=53.1301 C=90.0000 perimeter=6.0000 area=12.0000 height=4.0000 shouldUseDegrees 1

After I get the angles from my triangle object to use them, its description suddenly is as I would expect. I don't know if it has something to do with the custom setters and getters I'm using:

-(void) setAngleA:(double)angleA
{
    if (!_shouldUseDegrees){
        _angleA = angleA;
    }
    else _angleA = angleA * M_PI/180;
}
-(double) angleA
{
    if (!_shouldUseDegrees) {
        return _angleA;
    }
    return  _angleA *= 180/M_PI;
}

or my description method

-(NSString *) description;
{

    return [NSString stringWithFormat:@"a=%.4f b=%.4f c=%.4f A=%.4f B=%.4f C=%.4f perimeter=%.4f area=%.4f height=%.4f shouldUseDegrees %i", _sideA , _sideB , _sideC , _angleA , _angleB , _angleC , self.area , self.perimeter , self.height ,_shouldUseDegrees];

}

Upvotes: 2

Views: 128

Answers (1)

paulmelnikow
paulmelnikow

Reputation: 17208

You have two problems.

First off, you need to stop reassigning _angleA in your accessor:

return  _angleA *= 180/M_PI;

That ought to be:

return  _angleA * 180/M_PI;

The other is that you want your printout in degrees. Since your instance variable is always holding radians, change _angleA, _angleB, _angleC to self.angleA, self.angleB, self.angleC to invoke your custom accessors instead of printing the values of the instance variables.

Upvotes: 2

Related Questions