【Object-C】Get / Set 方法

get /set 方法的作用
当类中的属性被设置为私有时,需要用get/set方法来存取属性。
set()是给属性赋值的,get()是取得属性值的 
被设置和存取的属性一般是私有 
主要是起到封装的作用,不允许直接对属性操作 
set()和get()不一定同时存在,看程序需求

File “person.m”
#import  <Foundation/Foundation.h>

@interface  person :  NSObject

{
   
  int  age ;
   
  int  height ;
   
  int  weight ;
 
}

//get set 方法的代替方法。可以看到,set/get方法创建虽然很简单,但是当属性很多的时候,大量冗余的代码带来
//的工作量就呵呵了。X-code 提供了一个快捷的办法,需要用get/set方法的属性直接用“@property 类型  name ”创建。
//这样就省去了自己敲各个属性get,set 方法的过程,用起来非常的快捷。
@property  int  age ;
@property  int  height ;
@property  int  weight ;

//get set  方法,
-(
int )age;
-(
void )setAge:( int ) newAge;
-(
int )height;
-(
void )setHeight:( int ) newHeight;
-(
int )weight;
-(void)setWeight:(int) newWeight;

//输出
-(void)display;
@end

File “person.m”
#import  "person.h"

@implementation  person

//与property相对应的,set/get实现方法可以简化为以下三行代码。形式为“@Synthesize 属性”
@synthesize  age ;
@synthesize  height ;
@synthesize  weight ;

//set、get方法实现
-( int )age
{
   
  return  age ;
}

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

-(
int )height
{
   
  return  height  ;
}

-(
void )setHeight:( int )newHeight
{
   
  height  = newHeight ;
}

-(
int )weight
{
   
  return  weight  ;
}

-(
void )setWeight:( int )newWeight
{
   
  weight  = newWeight ;
}


-(
void )display
{
   
  NSLog ( @"age = %i , height = %i , weight = %i" , age , height , weight );
}

@end

File mail.m"
#import  <Foundation/Foundation.h>
#include
  "person.h"

int  main( int  argc,  const  char  * argv[]) {
   
  @autoreleasepool  {
       
  // insert code here...
       
  NSLog ( @"Hello, World!" );
       
       
  person  *personone = [[ person  alloc  ] init ];
        [personone  display];
        [personone  setAge :  18 ];
        [personone  setWeight :  50 ] ;
        [personone  setHeight: 175] ;
        [personone display];
    }
   
  return  0 ;
}

输出结果:
2014-11-25 10:50:29.894 accesser[731:303] Hello, World!
2014-11-25 10:50:29.896 accesser[731:303] age = 0 , height = 0 , weight = 0
2014-11-25 10:50:29.897 accesser[731:303] age = 18 , height = 175 , weight = 50







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值