Reputation: 37
I have a question about the following code. The output is wrong: frac1
should be printing out "2/3", but instead its being overwritten to "3/7". I can't seem to figure out why its being overwritten.
#import <Foundation/Foundation.h>
// ---- INTERFACE -----
@interface Fraction : NSObject
-(void) print;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int) d;
@end
//------implementation section ------
@implementation Fraction
int numerator;
int denominator;
-(void) print{
NSLog(@"%i/%i", numerator,denominator);
}
-(void) setNumerator:(int)n{
numerator = n;
}
-(void) setDenominator:(int)d{
denominator = d;
}
@end
// ---------- EXECUTION--------
int main (int argc, char * argv[])
{
@autoreleasepool {
Fraction * frac1 = [[Fraction alloc]init];
Fraction * frac2 = [[Fraction alloc]init];
[frac1 setNumerator:2];
[frac1 setDenominator:3];
// set second fraction
[frac2 setNumerator:3];
[frac2 setDenominator:7];
NSLog(@"this is the value of frac1:");
[frac1 print];
NSLog(@"this is the value of frac2:");
[frac2 print];
}
return 0;
}
Upvotes: 1
Views: 63
Reputation: 112857
The problem is that numerator
and denominator
are being set as global variables, not instance variables. To make then instance variables enclose them in {} as part of the @implementation definition.
Fixed:
@implementation Fraction {
int numerator;
int denominator;
}
Output:
this is the value of frac1:
2/3
this is the value of frac2:
3/7
Upvotes: 3
Reputation: 917
Use this code:
@interface Fraction : NSObject
@property (assign, nonatomic) int numerator;
@property (assign, nonatomic) int denominator;
- (void)print;
@end
@implementation Fraction
- (void)setNumerator:(int)numerator {
if (_numerator != numerator) {
_numerator = numerator;
}
}
- (void)setDenominator:(int)denominator {
if (_denominator != denominator) {
_denominator = denominator;
}
}
-(void) print{
NSLog(@"%i/%i", _numerator, _denominator);
}
@end
// OUTPUT
2015-01-18 18:12:58.844 fraction[29486:2733137] this is the value of frac1:
2015-01-18 18:12:58.845 fraction[29486:2733137] 2/3
2015-01-18 18:12:58.846 fraction[29486:2733137] this is the value of frac2:
2015-01-18 18:12:58.846 fraction[29486:2733137] 3/7
In your case int numerator; int denominator; are global vars, not object properties.
Upvotes: 2