可写原子属性不能配对合成的setter / getter

时间:2015-03-29 12:54:51

标签: objective-c synthesize

我有以下Dog.h和Dog.m并在标题中收到错误。如何更改代码才能使其工作?真的很感激一些见解!

   #import <Foundation/Foundation.h>

@interface Dog : NSObject

@property int age;


-(void) setAge: (int) value;
-(int) returnAge;

@end



 #import "Dog.h"

@implementation Dog

@synthesize age;


-(void) setAge: (int) value
{
    age = value;
}

-(int) returnAge
{
    return age;
}

@end

1 个答案:

答案 0 :(得分:2)

 #import <Foundation/Foundation.h>

@interface Dog : NSObject

@property (nonatomic) int age;

@end



 #import "Dog.h"

@implementation Dog

@synthesize age = _age;


- (void)setAge:(int)age
{
    _age = age;
}

- (int)age
{
    return _age;
}

@end

_age变量只应在getter和setter方法中使用。如果您访问.m文件中其他位置的变量,则应使用ageself.age。从.m文件外部,您应该使用dog.age