黑马程序员——@property

 

 黑马程序员——@property

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

***@property***

  @property是编译器的指令

  就是用来告诉编译器要做什么

  @property告诉编译器声明属性的访问器。(getter/setter)方法

 

**@property用法**

  @property 类型名 方法名(去掉set的)

  例:@property int age;

  相当于进行了age的set和get方法声明:**

  -(void)setAge:(int)age;

  -(int)age;

@interface Person : NSObject

{

    int _age;

    NSString *_name;

}

@property int age;

@property NSString *name;

@end

  @property使用注意

   1.@property只能写在@interface @end中

   2.@property用来自动生成get.set方法声明

   3.告诉@property要生成get,set方法声明的成员变量类型是什么

   4.告诉@property要生成get,set方法是哪个属性的,属性名去掉下划线

 

***@synthesize***

@synthesize在m文件中定义set,get方法实现

  @synthesize age;//生成一个变量age

  相当于进行了age的set和get方法实现:

  @implementation Person

  -(void)setAge:(int)age{

  self->age=age;

  }

  -(int)age{

  return age;

  }

@end

  @synthesize 方法名 使用注意

   方法名一定要先在.h中@interface @end声明

 

@synthesize指定实例变量赋值:

@synthesize 方法名=实例变量名

当指定实例变量名以后,此时,再不会生成,也不会操作默认的实例变量了

@synthesize age=_b,weight=_weight;

等同于:

   @implementation Person

  -(void)setAge:(int)age{

  _b=age;

  }

  -(int)age{

  return _age;

  }

  @end

 

**如果两个实例变量类型一致

  可以写成:

  @property int age,weight;

  @synthesize age,weight;  

 

**@property增强使用**(注意是私有的,不能被子类继承

 只写@property,不写@synthesize

 增强作用:声明与实现

 操作的是带下划线的实例变量,如果没有下划线的实例变量,系统会帮我们生成

当在@property增强下时

**不足:当需要输入设置合理数据的情况下要重写set,get**

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

原文地址:https://www.cnblogs.com/gaozp/p/4913109.html