封装
利用封装可以提供一种方法给外界设置或者访问属性值,并且可以过滤属性赋值,比如下面set方法,使小于0的都等于1
#import <Foundation/Foundation.h>
@interface Student : NSObject
{
//@public
int age;
}
- (void)setAge:(int)newAge;
- (int)age;
- (void)study;
@end
@implementation Student
- (void)study{
NSLog(@"%d岁的学生在学习" ,age);
}
- (void)setAge:(int)newAge{
if (newAge <= 0){
newAge = 1;
}
age = newAge;
}
- (int)age{
return age;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Student *student = [Student new];
[student setAge:5];
NSLog(@"学生年龄:%d",[student age]);
[student study];
}
return 0;
}
- set方法名必须以set开头
- set后面跟成员变量的名称
- get方法,方法名与成员变量名一致