黑马程序员技术交流社区

标题: @property方法的介绍与使用 [打印本页]

作者: mazhichao    时间: 2015-7-4 17:32
标题: @property方法的介绍与使用
@property
        @property是便一起的指令
        @property告诉编译器声明属性的访问器(getter/setter)方法
        1、@property 使用格式
                @property  数据类型 方法名(set方法去掉set后的名字)
        2、作用
                1)在xcode4.4之前,用于帮助我们实现get/set方法的声明
  1. #import <Foundation/Foundation.h>

  2. @interface person : NSObject
  3. {
  4.     NSString *_name;
  5.     int _age;
  6. }
  7. @property NSString *_name;
  8. /*@property NSString *_name的作用就是代替下面语句
  9. -(void)setName:(NSString*)name;
  10. -(NSString*)name;
  11. */
  12. @property int _age;
  13. /*@property int _age的作用就是代替下面语句
  14. -(void)setAge:(int)age;
  15. -(int)age;
  16. */
  17. @end
复制代码
  1. #import "person.h"

  2. @implementation person
  3. //set方法
  4. -(void)setName:(NSString*)name
  5. {
  6.     _name = name;
  7. }
  8. -(void)setAge:(int)age
  9. {
  10.     _age = age;
  11. }

  12. //get方法
  13. -(NSString*)name
  14. {
  15.     return _name;
  16. }
  17. -(int)age
  18. {
  19.     return _age;
  20. }
  21. @end
复制代码

main函数的实现与正常实现一样,此处不做多余代码的粘贴
作者: yangzhen5352    时间: 2015-7-4 17:36
赞(≧▽≦)一下……
作者: mazhichao    时间: 2015-7-4 18:08
刚刚又学了@synthesize实现.m文件
  1. #import "person.h"

  2. @implementation person
  3. @synthesize name; //帮助生成变量name
  4. /*
  5. -(void)setName:(NSString*)name
  6. {
  7.     _name = name;
  8. }
  9. -(NSString*)name
  10. {
  11.     return _name;
  12. }*/
  13. @synthesize age;    //帮助生成变量age
  14. /*
  15. -(void)setAge:(int)age
  16. {
  17.     _age = age;
  18. }
  19. -(int)age
  20. {
  21.     return _age;
  22. }*/
  23. @end
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2