OC中类的成员变量默认是@protect,外界无法访问类的成员变量,所以通常我们在类文件中声明变量时会同时声明setter跟getter两个方法方便我们获取变量和修改(下面所有代码均在ARC模式下实现)
Person.h文件
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
int _age;
NSString * _name;
}
- (void)setAge: (int)age; //setter方法
- (int)age; //getter方法
- (void)setName: (NSString *)name;
@end
Person.m文件#import "Person.h"
@implementation Person
- (void)setAge: (int)age
{
_age = age;
}
- (int)age
{
return _age;
}
- (void)setName: (NSString *)name
{
_name = name;
}
@end
Main.m文件
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
int _age;
NSString * _name;
}
- (void)setAge: (int)age; //setter方法
- (int)age; //getter方法
- (void)setName: (NSString *)name;
@end
#import "Person.h"
@implementation Person
- (void)setAge: (int)age
{
_age = age;
}
- (int)age
{
return _age;
}
- (void)setName: (NSString *)name
{
_name = name;
}
@end