Reputation: 21
I want to create an instance variable called "pi" of class "Circle" and set its value of 3.14 as a constant that once is set cant be changed and classes inheriting the Circle class will also get pi variable without needing to set its value each time;
My Code:
#import <Foundation/Foundation.h>
@interface Circle: NSObject
{
const double pi = 3.14;
}
@property float radius;
-(float) area;
-(float) perimeter;
@end
Upvotes: 1
Views: 395
Reputation: 438082
If it's not really something that is not unique to any particular instance, I might use a class
property (or class method):
@property (class, readonly) double pi;
And then I'd implement a custom getter to return the value in question:
+ (double)pi {
return M_PI;
}
Or, if it involved complicated calculation, then you might use the dispatch_once
pattern so it's only calculated once:
+ (double)pi {
static dispatch_once_t once;
static double _pi = 0;
dispatch_once(&once, ^{
// an unnecessary complicated calculation of pi, just to illustrate we'll do this only once
int k = 1;
double previous = 0;
BOOL sign = TRUE;
do {
previous = _pi;
_pi = previous + 4.0 * (sign ? 1.0 : -1.0) / k;
k += 2;
sign = !sign;
} while (fabs(_pi - previous) > 0.0001);
});
return _pi;
}
And then you can reference this pi
property:
- (float)area {
return self.radius * self.radius * [Circle pi];
}
- (float)perimeter {
return self.radius * [Circle pi] * 2.0;
}
Upvotes: 1