0%

Objective-C 自动封装类的属性

以Student类为例.该类包含一个int 学生ID,float 分数,以用print 打印方法. Student.h:

#import 

@interface Student : NSObject
{
    int sId;
    float score;
}
@property int sId;
@property float score;
//这两行是关键,把需要封装的属性都加上,相同类型可写在一行
//如果不是基本类型的变量,需要增加copy,nonatomic 参数,如
//@property (copy,nonatomic) NSString * nickname,* email;
//这样使用setter方法会复制值,而不是复制引用

-(void)print;
@end

Student.m:

#import "Student.h"

@implementation Student
-(void) print
{
    NSLog(@"%d  %f",sId,score);
    
}
@synthesize sId,score;
//上面一行是关键
@end

封装后,可以通过下面的方法访问属性: s1为Student的实例 读取属性: [s1 sId]或s1.sId 赋值: s1.sId=10 或[s1 setSId:10] 后面的setSId方法是自动生成的,方法名为set加属性名,但是第一个字母改为大写.