2011-07-27 39 views
0

我正在從一本書中得到一個例子,它似乎並沒有工作我收到警告不完整的實現。當我運行該程序時,出現錯誤信息「EXC_BAD_ACCESS」。該警告在行return [NSString stringWithFormat:@"Name:...的.m文件中有沒有人知道我在做什麼錯了?不完整的實現示例幫助!

我.m文件

#import "RadioStation.h" 


@implementation RadioStation 

+ (double)minAMFrequency { 
    return 520.0; 
} 

+ (double)maxAMFrequency { 
    return 1610.0; 
} 

+ (double)minFMFrequency { 
    return 88.3; 
} 

+ (double)maxFMFrequency { 
    return 107.9; 
} 

- (id)initWithName:(NSString *)newName atFrequency:(double)newFreq atBand:(char)newBand { 
    self = [super init]; 
    if (self != nil) { 
     name = [newName retain]; 
     frequency = newFreq; 
     band = newBand; 
    } 

    return self; 
} 

- (NSString *)description { 
    return [NSString stringWithFormat:@"Name: %@, Frequency: %.1f Band: %@", name, frequency, band]; 
} 

- (void)dealloc { 
    [name release]; 
    [super dealloc]; 
} 

@end 

我.h文件中

radiosimulation.m文件:

int main (int argc, const char * argv[]) { 
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 

    // insert code here... 
    NSMutableDictionary* stations = [[NSMutableDictionary alloc] init]; 
    RadioStation* newStation; 

    newStation = [[RadioStation alloc] initWithName:@"Star 94" 
             atFrequency:94.1 
              atBand:'F']; 

    [stations setObject:newStation forKey:@"WSTR"]; 
    [newStation release]; 

    NSLog(@"%@", [stations objectForKey:@"WSTR"]); 

    newStation = [[RadioStation alloc] initWithName:@"Rocky 99" 
             atFrequency:94.1 
              atBand:'F']; 

    [stations setObject:newStation forKey:@"WKFR"]; 
    [newStation release]; 

    NSLog(@"%@", [stations objectForKey:@"WKFR"]); 

    [stations release]; 
    [pool drain]; 
    return 0; 
+2

調試器中的堆棧跟蹤會告訴你你在哪裏得到'EXC_BAD_ACCESS'。如果您在此處發佈堆棧跟蹤,我們將能夠提供更多幫助。 – highlycaffeinated

+0

你在哪一行得到警告? – taskinoor

+0

@highlycaffeinated如何訪問堆棧跟蹤> – iPhoneDev85

回答

5

您聲明如下屬性訪問器/增變器(getter/setter),但沒有在你的.m文件中實現它們。

-(NSString *)name; 
-(void)setName:(NSString *)newName; 
-(double)frequency; 
-(void)setFrequency:(double)newFrequency; 
-(char)band; 
-(void)setBand:(char)newBand; 

您需要實現的.m文件,這些方法都6,如果你想刪除有關完全執行警告。

您在.h文件中有效地說,這是您的對象將要執行的操作,然後不在.m中執行。它不會產生錯誤,因爲objective-c消息傳遞意味着消息將傳遞給NSObject進行處理,這也將沒有任何匹配的實現,並且這些消息將被默默地忽略。我不喜歡這只是一個警告 - 但你去了。

這麼說,我不會創建這樣的屬性(有使用@property在Objective-C這樣的整潔的方式),我會刪除在.H這些方法的聲明,並取代它們:

@property (nonatomic, retain) NSString *name; 
@property (nonatomic, assign) double frequency; 
@property (nonatomic, assign) char band; 

這些屬性聲明與方法聲明位於同一位置。

,然後添加以下.m文件:

@synthesize name; 
@synthesize frequency; 
@synthesize band; 

這將避免不必編寫您當前丟失所有的樣板訪問/突變代碼。再次,這些代碼與方法實現位於同一個代碼區域。編譯器將有效地自動創建名稱和setName方法。

這段代碼沒有經過測試 - 但應該指出你整理不完整實現的正確方向。它可能也修復您的訪問錯誤 - 但這可能需要更詳細的看一下堆棧跟蹤。

另一點我不確定編寫的代碼甚至需要使用get/set方法或屬性。您可以嘗試從.h中刪除方法聲明並查看它是否有效。似乎所有對名稱,頻率和頻帶的訪問都來自對象內部。