黑马程序员技术交流社区

标题: oc的get/set方法 [打印本页]

作者: c9527    时间: 2015-11-4 09:30
标题: oc的get/set方法
Setter函数

setter函数,对成员变量赋值。Set函数的一般写法以对age操作为例,写法为:

-(void)setName:(NNString*)name;    //声明setter函数

Get函数

getter函数,对成员变量取值。Get函数的一般写法也以对age的操作为例,写法为:

-(int)age;                  //声明getter函数

具体实现如下例子:

Person.h

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

@end  


Person.m

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

- (int) age  
{  
    return age;  
}  

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

@end  


main.m

#import <Foundation/Foundation.h>
#import "Person.h"
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;  
}  





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2