OC语言学习 (三) 成员变量get/set方法和“.”语法,@proterty和@synthesize关键字

Person.h

#ifndef oc_Person_h
#define oc_Person_h

@interface Person : NSObject
{
    int age;
@protected
    float height;
}
- (int) age; //get方法
- (void) setAge:(int)pAge;  //set方法

@end

#endif

Person.m

#import <Foundation/Foundation.h>
#import "Person.h"
@implementation Person

- (int) age
{
    return age;
}

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

@end

main.m

int main()
{
    Person* per = [[Person alloc] init];
    int age = [per age]; //调用get方法
    [per setAge:16]; //调用set方法
    
    //使用“.” 来调用get/set  使用的都是原始变量名,这就要求变量的get、set都符合约定
    int age2 = per.age; //get
    per.age = 17; //set
    
    return 0;
}

每次这样写get/set方法,很麻烦,OC有一个自动化的方法,即使用 @proterty @synthesize 关键字

Person.h

#ifndef oc_Person_h
#define oc_Person_h

@interface Person : NSObject
{
    int age;
@protected
  //  float height;
}
//- (int) age;
//- (void) setAge:(int)pAge;

@property int age; //编译器自动解释成 int age的get/set方法 的声明。
//@property int age = _age;//如果没有指定成员变量名,实现中默认访问的同名的成员变量age
@property float height;  //如果height没有声明,而用在这里, 也会自动生成以height为标准名的 get/set方法
@end

#endif

Person.m

#import <Foundation/Foundation.h>
#import "Person.h"
@implementation Person

//- (int) age
//{
//    return age;
//}
//
//- (void) setAge:(int)pAge
//{
//    age = pAge;
//}
@synthesize age; //编译器自动解释成 age的get、set方法实现。  在xcode4.5之后可以不写这句话
@synthesize height = _height; //如果_height不存在,会生成一个私有的_height变量
@end





评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值