我似乎无法解决这个错误;使用未声明的标识符“ageBy”。
我不明白为什么要得到它,因为我的代码中有导入Person.h。
感谢您的宝贵时间和任何帮助。


@interface Person : NSObject
{
 int _age;
 int _years;
 NSString *_name;
 NSString *_job;

}

-(void)setAge:(int)age;
-(int)age;

-(void)setName:(NSString *)name;
-(NSString *)name;

-(void)setJob:(NSString *)job;
-(NSString *)job;

-(NSString *)summaryString;

-(void)ageBy:(int)years;


@end


#import "Person.h"
@implementation Person

-(void)setAge:(int)age{
  _age = age;
}
-(int)age{
  return _age;
}
-(void)setName:(NSString *)name{
  _name = name;
}
-(NSString *)name{
  return _name; }

-(void)setJob:(NSString *)job{
  _job = job;
}
-(NSString *)job{
  return _job;
}

-(NSString *)summaryString{
  return [NSString stringWithFormat:@"The Person %@ is %d years old and is a  %@",_name,_age,_job];

-(void)ageBy:(int)years{
  _years = years;
  _age = years + _age;

 }

 }
 @end

最佳答案

您的ageBy:是在summaryString中定义的。您可能希望将大括号移到@end之前,使其位于-(void)ageBy:(int)years上方。所以:

-(NSString *)summaryString{
  return [NSString stringWithFormat:@"The Person %@ is %d years old and is a  %@",_name,_age,_job];
 }

-(void)ageBy:(int)years{
  _years = years;
  _age = years + _age;

 }

另外,作为样式说明,如果summaryString仅用于调试,那么最好将其声明为 description 。后者是获取Objective-C对象的实现依赖和字符串描述的标准形式,其最终效果是像NSArray这样的集合对象知道在所有子对象上调用description来创建正确的输出。

10-08 17:50