【语法】@property和@synthesize

@property【写在.h文件里】

  @property是让编译器自动产生函数声明                                                                                      

不用写下面2行代码

  -(void)setAge:(int)newAge;

  -(int)age;

只需要下面一列就可以代替

  @property int age;

 

@synthesize【写在.m文件里】

  @synthesize就是编译器自动实现getter和setter函数                                                                 

不用写下列6行代码

  -(void)setAge:(int)newAge{

  age=newAge;

  }

  -(int)age{

  return age;

  }

只需要写

@synthesize age;

 

【例子】.h文件

 1 //
 2 //  dog.h
 3 //  pro3
 4 //
 5 //  Created by 裴烨烽 on 14-1-24.
 6 //  Copyright (c) 2014年 裴烨烽. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 
11 @interface dog : NSObject
12 {
13     int age;
14 }
15 
16 //-(void)setAge:(int)newAge; 【(1)】
17 //-(int)age;                 【(2)】
18 @property int age;           【(1)+(2)】这一句话就是上面的两句的和
19 
20 @end

.m文件

 

 1 //
 2 //  dog.m
 3 //  pro3
 4 //
 5 //  Created by 裴烨烽 on 14-1-24.
 6 //  Copyright (c) 2014年 裴烨烽. All rights reserved.
 7 //
 8 
 9 #import "dog.h"
10 
11 @implementation dog
12 //-(void)setAge:(int)newAge{      【(1)】
13   //  age=newAge;           【(2)】
14 //}                   【(3)】
15 //-(int)age{             【(4)】
16   //  return age;          【(5)】
17 //}                  【(6)】
18 
19 //上面注释的几行可以用下面这行代替
20 
21 @synthesize age;             【(1)】+【(2)】+【(3)】+【(4)】+【(5)】+【(6)】  这一句就是上面六句话的和
22 @end

 

 

posted @ 2014-01-24 21:10  太过于漂流  阅读(256)  评论(0编辑  收藏  举报