zoukankan      html  css  js  c++  java
  • OC基础--关键字@property 和 @synthesize

    一、@property关键字需要掌握的知识:

    1.用在@interface中,用来自动生成setter和getter的声明

    例:@property int age;--相当于执行了右边的代码-->-(void) setAge:(int) age;  -(int) age;

    二、@synthesize关键字需要掌握的知识:

    1.用在@implementation中,用来自动生成setter和getter的实现

    例:@synthesize age = _age;

    2.注意:在  @synthesize age = _age;  中如果没有指定成员变量名,实现中默认访问的就是同名的成员变量

    例: @synthesize age;//默认访问的就是age成员变量,而不是_age成员变量

    如果age这个成员变量不存在,程序会在@implementation中自动生成一个私有的age变量

    同理,如果指定的成员变量也不存在,程序也会在@implementation中自动生成一个私有的跟指定变量同名的成员变量

    三、Xcode版本注意事项:

    1.Xcode 4.4前:关键字@property 只是自动生成set方法和get方法的声明

    2.Xcode 4.4后:关键字@property 将会自动生成set方法和get方法的声明和实现、增加一个_开头的成员变量

    四、代码实例:

    #import <Foundation/Foundation.h>
    
    @interface Car : NSObject
    {
        int _wheels;
        //int _speed;
    }
    @property int wheels;
    @property int speed;
    @end
    
    @implementation Car
    // 默认会访问wheels成员变量,如果这个成员变量不存在,自动生成一个私有的wheels变量
    @synthesize wheels;
    
    // setter和getter会访问_speed成员变量,如果这个成员变量不存在,自动生成一个私有的_speed变量
    @synthesize speed = _speed;
    
    - (NSString *)description
    {
        return [NSString stringWithFormat:@"wheels=%d,_speed=%d", wheels, _speed];
    }
    
    @end
    
    int main()
    {
        Car *c = [[Car alloc] init];
        
        c.wheels = 4;
        c.speed = 250;
    
        
        NSLog(@"%@", c);
        //NSLog(@"轮子个数:%d", c.wheels);
        
        return 0;
    }
    

      

  • 相关阅读:
    C#随机数的使用
    英才评测 个人性格倾向 IT知识
    有点迷茫
    [转帖]2006年it人士必去的10个网站
    ASP.NET 中 Cookie 的基本知识
    Http请求方法
    Spherical Mercator
    Axure快速原型设计
    【转】Spring Insight 使用介绍
    DB2执行sql文件
  • 原文地址:https://www.cnblogs.com/gchlcc/p/5179956.html
Copyright © 2011-2022 走看看