2

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

人.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

人.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
4

2 回答 2

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其所有子对象以创建正确的输出。

于 2012-11-25T19:56:09.913 回答
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
于 2012-11-25T20:30:57.567 回答