我目前正在学习Objective-C。我创建了一个类来保存有关汽车的信息(BasicCar)。还创建了一个子类来保存汽车的颜色和门数(ExtendedCar)。除门的数量外,所有属性均为文本(NSString
),类型为int
。
我的父班:
#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'数据做一些事情。
答案 0 :(得分:2)
正如Jeremy在评论中所说,你使用了错误的格式说明符。 %@
是obj-c对象的格式说明符。这对于make
,model
和color
是正确的,但它对doors
不正确,因为它是C原始数据类型(int
)。 int
的正确格式说明符为%i
(或%d
)。
NSLog(@"Make: %@, Model: %@, Color: %@, Doors: %d \n\n",[myCar1 make],[myCar1 model],[myCar1 color], [myCar1 doors]);
NSLog(@"Make: %@, Model: %@, Color: %@, Doors: %d \n\n",[myCar2 make],[myCar2 model], [myCar2 color], [myCar2 doors]);
答案 1 :(得分:0)
格式%@
仅用于输出Objective C对象,而不是整数。
根据Apple的String Format Specifier list,输出整数的正确格式为%d
。
答案 2 :(得分:0)
你应该替换
NSLog(@"Make: %@, Model: %@, Color: %@, Doors: %@ \n\n",[myCar1 make],[myCar1 model],[myCar1 color], [myCar1 doors]);
通过
NSLog(@"Make: %@, Model: %@, Color: %@, Doors: %i \n\n",[myCar1 make],[myCar1 model],[myCar1 color], [myCar1 doors]);
%@
已被%i
取代:您可以在此处找到相关说明:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html