IOS之Objective-C学习笔记(四)

@property 与  @synthesize


 之前一个小列子:

@interface Student :NSObject{

     int age;

}

@end


-(void)setAge:(int)newAge;

-(int)age;


--------类的实现-----------

@implementation Student

 -(void)setAge:(int)newAge{

     age =newAge;

}

-(void)age{

   return age;

}

@end


使用age做为成员变量 ,get ,set方法为外部提供一个可访问的属性。

如果成员变量很多个,那么就会有很多个get ,set 方法,这样代码会冗余


怎么解决这个问题呢?



这里提供了一个语法:@property;     

当编辑器遇到@property  ,会自动展开成getter和setter方法,不用在写-(void)setAge:(int)newAge; -(void)age:(int)age;

@property 自动会生成get,set方法。


在.m文件中 对getter和setter方法实现  ,可以使用@synthesize;

@synthesize age;

//@synthesize age,height,width; 可以连接写多个属性。


@propery只能使用在interface文件中

@synthesize 只能使用在implementation中


 @interface Person:NSObject{

   int _ID;

   float _weight;

}

@propery int ID;

@property float weight;

@end


在.m文件

@implementation Persion

@synthesize ID= _ID;  //编辑器会默认生成_ID   - -get和set方法  这是私有的。如果想公共的,需要声明.h声明成员变量

@synthesize weight=_weight;

@end




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值