Reputation: 2609
I am learning Objective-C inheritance and my program is getting lost in a recursive loop and won't come out. It gets hung up when calling a getter function.
I am using XCode version: Version 6.2 (6C101)
My program is given below
Vehicle.h
#ifndef exercise_2_Vehicle_h
#define exercise_2_Vehicle_h
#import <Foundation/Foundation.h>
@interface Vehicle : NSObject
@property float speed;
-(void) start;
-(void) stop;
-(void) park;
@end
#endif
Vehicle.m
#import "Vehicle.h"
@implementation Vehicle
-(void) setSpeed:(float)speed {
self.speed = speed;
}
-(float) speed {
return self.speed;
}
-(void) start {
NSLog(@"Starting the vehicle");
}
-(void) stop {
NSLog(@"Stopping the vehicle");
}
-(void) park {
NSLog(@"Parking the vehicle");
}
@end
Car.h
#ifndef exercise_2_Car_h
#define exercise_2_Car_h
#import "Vehicle.h"
@interface Car : Vehicle
@property (nonatomic) NSString* make;
-(Car*) initMake: (NSString*) make;
-(NSString*) make;
@end
#endif
Car.m
#import "Car.h"
@implementation Car
-(Car*) initMake:(NSString *)make {
self = [super init];
if (self) {
self.make = make;
}
return self;
}
-(NSString*) make {
return self.make;
}
@end
main.m
#import <Foundation/Foundation.h>
#import "Car.h"
#import "Vehicle.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
Car* car = [[[Car alloc] init] initMake: @"Camry"];
//[car setSpeed:45];
NSLog(@"The model initialized is ");
[car make];
// [car speed];
}
return 0;
}
Upvotes: 0
Views: 258
Reputation: 776
In the
- (NSString*)make;
use
return _make
instead. The same with the speed.
If you return "self.x" in a getter method, then it's going to try and call the method again because you're requesting it on self. XCode will automatically convert the properties into variables that can be accessed with an '_' character, so you don't need to do any extra work.
You could also ignore our advice and remove both the "speed" and "make" getter methods you have made, because XCode automagically creates them for you.
Upvotes: 1
Reputation: 25459
The issue you have is caused by creating the property for speed:
@property float speed;
and overriding setSpeed:
method.
When you create @property compiler adds two methods for you, in your example setSpeed and speed. This command:
self.speed = speed;
is equal to:
[self setSpeed: speed];
and inside setSpeed you have this command again which cause the loop. In your example you can remove both methods (setSpeed and speed) because compiler will add it for you. If you need it because you want to do some customisation you should use _speed instead self.speed. _speed is backed variable added by compiler when using @property. Change your method to:
-(void) setSpeed:(float)speed {
_speed = speed;
}
to remove the infinite loop.
Upvotes: 1