• OC的@property 和 @synthesize id


    学习java的JDBC,成员变量的setter和getter,eclipse都能帮我们自动生成;当然xcode这款编译器也很强大,也能自动生成;

    1:@property 

         @property是写在类的声明中的,具体写法;

    @interface  Person : NSObject
    {
          _age;
    }
    @property int age; // 这句话相当于下边的getter和setter,但是注意age没有'_',但是就是为有下划线的age生成的,这样方便了点语法的调用;
    // - (void)setAge:(int)age;
    // - (int)age;
    @end

    所以写法:@property   (成员变量的类型) 去掉下划线的成员变量名

    2:@synthesize:setter和getter方法的实现,在implementation中;

    @implementation
    
    @synthesize  age = _age; // 注意格式,等号左边表示实现age的setter和getter,即 setAge  和  age; 等号右边表示访问那个成员变量;
    
    // 代替了下面这两个方法;
    /*
    - (void)setAge:(int)age
    {
           _age = age;
    }
    - (int)age
    {
          return _age;
    }
    */
    @end

    3:@property  @synthesize后边可以同时并列多个成员变量,前提是这几个成员变量的类型一样

    // @property写法
    @property  int age, weight; // 以逗号分隔,前提是age和weight都是int型的;
    // @synthesize写法
    @synthesize age = _age, weight = _weight; 

    4:如果自己没有明确的定义成员变量,比如_age,然后写了@property int age;这句话会自动为我们生成_age这个成员变了,但是它的访问权限是private的

    5:现在版本的@property功能更强大,独揽了setter和getter的声明和实现;可以只写@property,而不用写@synthesize,xcode也会自动生成setter和getter的声明与实现,并且你也可以不用定义成员变量,它也能自动为我们生成带有下划线的成员变量,只不过是private的;

    @interface Student : NSObject
    @property int age; // 这句话做了3件事
    /*
    1:为我们生成了_age这个成员变量,private的;
    2:声明了age得setter和getter方法;
    3:在implementation中实现了setter和getter
    */
    @end

    @property  @synthesize的使用注意;

       如果@synthesize age;  这样写 他会访问的时和age同名的成员变量,不会访问_age;  如果没有age,他会自动生成@private的age;

       方法也是一样,如果setter和getter我们自己写了,它会优先用我们自己写得,如果没有,它才会自动生成;xcode的特性就是这样,优先选择我们自己写得,如果我    们没写,它才自动生成;

    id

    万能指针,能指向任何OC对象,定义方式:id d = [Person new];注意定义时不要加*;如果说OC中所有的类都继承了NSObject,那么id相当于: NSObject *;

         

  • 相关阅读:
    Oracle用户管理
    Oracle基本使用
    Oracle 11g安装、卸载
    Oracle
    C#面向对象
    看看Google用户体验十大设计原则
    [转]Delphi 常用控件之TlistView总结
    github + hexo 搭建博客
    CSS3 filter属性学习
    border-box——一种改变盒子尺寸的方法
  • 原文地址:https://www.cnblogs.com/cxbblog/p/3720793.html
Copyright © 2020-2023  润新知