I am currently learning Objective-C. I have created a class to hold information about cars (BasicCar). Also created a child class to hold the car’s color and amount of doors (ExtendedCar). All properties are text (NSString) except for the amount of doors, which is of type int.
My parent class:
#import <Foundation/Foundation.h>
#import <cocoa/cocoa.h>
@interface BasicCar : NSObject {
NSString *make;
NSString *model;
}
@property (readwrite, retain) NSString* make;
@property (readwrite, retain) NSString* model;
@end
#import "BasicCar.h"
@implementation BasicCar
@synthesize make;
@synthesize model;
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
@end
My child class:
#import <Foundation/Foundation.h>
#import <cocoa/cocoa.h>
#import "BasicCar.h"
@interface ExtendedCar : BasicCar {
NSString* color;
int doors;
}
@property (readwrite,retain) NSString* color;
@property (readwrite) int doors;
@end
#import "ExtendedCar.h"
@implementation ExtendedCar : BasicCar
@synthesize color;
@synthesize doors;
@end
My main code:
#import <Foundation/Foundation.h>
#import "BasicCar.h"
#import "ExtendedCar.h"
int main (int argc, const char * argv[])
{
ExtendedCar *myCar1 = [[ExtendedCar alloc]init];
NSString *carMake = @"BMW";
NSString *carModel = @"M5";
NSString *carColor = @"blue";
int carDoors = 4;
[myCar1 setMake:carMake];
[myCar1 setModel:carModel];
[myCar1 setColor:carColor];
[myCar1 setDoors:carDoors];
ExtendedCar *myCar2 = [[ExtendedCar alloc]init];
carMake = @"Hummer";
carModel = @"H3";
carColor = @"green";
carDoors = 4;
[myCar2 setMake:carMake];
[myCar2 setModel:carModel];
[myCar2 setColor:carColor];
[myCar2 setDoors:carDoors];
NSLog(@"Make: %@, Model: %@, Color: %@, Doors: %@ \n\n",[myCar1 make],[myCar1 model],[myCar1 color], [myCar1 doors]);
NSLog(@"Make: %@, Model: %@, Color: %@, Doors: %@ \n\n",[myCar2 make],[myCar2 model], [myCar2 color], [myCar2 doors]);
return 0;
}
Now when I debug it, I get an EXC_BAD_ACCESS error in Xcode at this line:
NSLog(@"Make: %@, Model: %@, Color: %@, Doors: %@ \n\n",[myCar1 make],[myCar1 model],[myCar1 color], [myCar1 doors]);
Why is this happening and what can I do to fix this? It does not happen when I remove the ‘doors’ part, so it has to do something with the ‘int’ data.
As Jeremy said in a comment, you’re using the wrong format specifier.
%@is the format specifier for obj-c objects. This is correct formake,model, andcolor, but it’s not correct fordoorsbecause that’s a C primitive datatype (int). The correct format specifier forints is%i(or%d).