我正在做我得到的一本书中的一个例子,它似乎不起作用,我得到了未完成实现的警告。当我运行程序时,我得到一个错误信号"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文件
#import <Cocoa/Cocoa.h>
@interface RadioStation : NSObject {
NSString *name;
double frequency;
char band;
}
+ (double)minAMFrequency;
+ (double)maxAMFrequency;
+ (double)minFMFrequency;
+ (double)maxFMFrequency;
-(id)initWithName:(NSString*)name
atFrequency:(double)freq
atBand:(char)ban;
-(NSString *)name;
-(void)setName:(NSString *)newName;
-(double)frequency;
-(void)setFrequency:(double)newFrequency;
-(char)band;
-(void)setBand:(char)newBand;
@endradiosimulation.m ation.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;发布于 2011-07-27 23:50:59
您声明了以下属性访问器/变更器(getter/getter),但没有在.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处理,它也将没有任何匹配的实现,并且消息将被静默忽略。我不喜欢这种方式,这只是一个警告-但你就是这样。
也就是说,我不会创建这样的属性(在objective-c中使用@property有更好的方法来做到这一点),我会删除.h中的那些方法声明,并将它们替换为:
@property (nonatomic, retain) NSString *name;
@property (nonatomic, assign) double frequency;
@property (nonatomic, assign) char band;这些属性声明与方法声明位于相同的位置。
然后将以下内容添加到.m文件中:
@synthesize name;
@synthesize frequency;
@synthesize band;这将避免编写当前缺少的所有样板访问器/赋值器代码。同样,这些代码与方法实现位于相同的代码区域。实际上,编译器将自动创建name和setName方法。
这段代码是未经测试的--但它可以为你指明正确的方向来整理未完成的实现。它可能也会修复您的访问错误-但这可能需要对堆栈跟踪进行更详细的检查。
还有一点,我不确定代码是否需要使用get/方法或属性。您可以尝试从.h中删除方法声明,看看它是否有效。似乎所有对名称、频率和频段的访问都来自对象内部。
https://stackoverflow.com/questions/6847214
复制相似问题