2012-03-14 70 views
0

我目前正在學習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'數據執行某些操作。

+0

退出提示:可以肯定的打印整數時使用正確的格式說明符。使用%i而不是%@。 – Jeremy 2012-03-14 19:58:03

回答

2

正如Jeremy在評論中所說的,你使用了錯誤的格式說明符。 %@是obj-c對象的格式說明符。這對於make,modelcolor是正確的,但它對於doors不正確,因爲這是C原始數據類型(int)。 int s的正確格式說明符是%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]); 
+0

感謝您的幫助,現在工作正常:) – user1269955 2012-03-15 10:11:45

0

格式%@僅適用於輸出Objective C對象,不適用於整數。

根據Apple的String Format Specifier list,輸出整數的正確格式爲%d

相關問題