I’m working on one simple objective-c program which contain categories. My class .h:
#import <Foundation/Foundation.h>
@interface Fraction : NSObject
@property int numerator, denominator;
-(void)setNumerator:(int)n andDenominator:(int)d;
@end
In .m file I synthesized my numerator and denominator. In main.m created category of my Fraction class:
#import "Fraction.h"
@interface Fraction (MathOps)
-(Fraction *) add: (Fraction *) f;
@end
@implementation Fraction (MathOps)
-(Fraction *) add: (Fraction *) f
{
// To add two fractions:
// a/b + c/d = ((a*d) + (b*c)) / (b * d)
Fraction *result = [[Fraction alloc] init];
result.numerator = (numerator * f.denominator) +
(denominator * f.numerator);
result.denominator = denominator * f.denominator;
[result reduce];
return result;
}
@end
But my program does not see numerator and denominator in category’s implementation section. Error “Use of undeclared identifier ‘numerator'(the same for denominator). What am I doing wrong?
Use the properties instead of using the ivars directly:
The instance variables aren’t visible to your category because they’re not declared in Fraction’s interface — they’re only created when you @synthesize them in your implementation. That leads to the other possible solution, which is to declare the instance variables in Fraction’s interface: