Reputation: 547
I can't seem to get round this error; use of undeclared identifier 'ageBy'. I dont understand why am getting it as i have the import Person.h in my code. Thanks for your time and any help.
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
Upvotes: 2
Views: 9274
Reputation: 318904
As was stated, the problem is caused by the ageBy:
method being embedded in the summaryString
method.
I wanted to demonstrate how this class could be written using modern 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
Upvotes: 4
Reputation: 100662
Your ageBy:
is defined inside summaryString
. You probably want to move the curly bracket just before @end
so that it is above -(void)ageBy:(int)years
. So:
-(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;
}
Also as a style note, if summaryString
is merely for debugging then you'd possibly be better off declaring it as description
. The latter is the standard form for getting an implementation-dependand string description of an Objective-C object, with the net effect that collection objects like NSArray
know to call description
on all their child objects in order to create the correct output.
Upvotes: 4