zoukankan      html  css  js  c++  java
  • 【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







  • 相关阅读:
    高可用Redis服务架构分析与搭建
    Java 程序性能问题
    限流、熔断、服务降级理解
    设计模式-享元设计
    设计模式-原型设计
    java8 Stream原理
    SQL语句性能优化策略
    OAuth2和JWT
    5种常见的Docker Compose错误
    leetcode_699. 掉落的方块
  • 原文地址:https://www.cnblogs.com/shujucn/p/7481465.html
Copyright © 2011-2022 走看看