我目前正在學習Objective-C。我創建了一個類來保存關於汽車的信息(BasicCar)。還創建了一個小孩班來保存車的顏色和門的數量(ExtendedCar)。所有屬性均爲文字(NSString
),門數除外,其類型爲int
。類中的Objective-C int數據類型給出了EXC_BAD_ACCESS錯誤
我的父類:
#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
我的子類:
#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
我的主要代碼:
#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;
}
現在,當我調試它,我得到在Xcode的EXC_BAD_ACCESS錯誤在這條線上:
NSLog(@"Make: %@, Model: %@, Color: %@, Doors: %@ \n\n",[myCar1 make],[myCar1 model],[myCar1 color], [myCar1 doors]);
爲什麼會發生這種情況,我該如何解決這個問題?當我移除'門'部分時,它不會發生,所以它必須對'int'數據執行某些操作。
退出提示:可以肯定的打印整數時使用正確的格式說明符。使用%i而不是%@。 – Jeremy 2012-03-14 19:58:03