我似乎无法解决这个错误;使用未声明的标识符'ageBy'。 我不明白为什么我得到它,因为我在我的代码中有导入Person.h。 感谢您的时间和任何帮助。
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
Person.m
#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
答案 0 :(得分:4)
您的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
的净效果,以便创建正确的输出。
答案 1 :(得分:4)
如上所述,问题是由ageBy:
方法中嵌入summaryString
方法引起的。
我想演示如何使用现代Objective-C编写这个类:
// Person.h
@interface Person : NSObject
@property (nonatomic, assign) int age;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *job;
- (void)ageBy:(int)years;
@end
// Person.m
@implementation Person
- (NSString *)description {
return [NSString stringWithFormat:@"The Person %@ is %d years old and is a %@", self.name, self.age, self.job];
}
- (void)ageBy:(int)years {
self.age = self.age + years;
}
@end