首页 > 其他 > 详细

property和synthesize

时间:2014-01-29 01:01:34      阅读:399      评论:0      收藏:0      [点我收藏+]

property和synthesize 是编译器为了开发者写更少的垃圾重复代码而提高开发效率,依赖于编译器的环境,很像Java中的注解,也需要在jdk5.0以后才可以使用,@property主要是在.h文件中声明setter和Getter方法,而@synthesize是在.m文件中实现标准的setter和Getter方法。

@property

#import <Foundation/Foundation.h>


@interface Student :NSObject{

   int _age; //可以省略

   int _no;//可以省略

}


@propertyint age;//展开生成setterGetter方法

@property int no;

//-(void)setAge:(int)newAge;

//-(int)age;


//-(void)setNo:(int)newNo;

//-(int)no;


@end


@synthesize

#import "Student.h"


@implementation Student

//@synthesize age,no;

//setterGetter方法会去访问成员变量_age

@synthesize age=_age;

//-(void)setAge:(int)newAge{

//    age=newAge;

//}

//

//-(int)age{

//    return age;

//}


@synthesize no=_no;


@end



在开发中,很多时候需要在setter方法中处理一些自定义的功能,这个时候就需要我们手动实现setter方法了,而@property和@synthesize可以混搭使用,如下图所示

bubuko.com,布布扣

注意点:

1.@synthesize生成setterGetter的实现,和property一一对应,默认访问property对应的age,如果找不到同名的变量,会自动生成一个私有同名变量,.h文件中的成员变量可以省略

2.如果在m文件中手动实现了setter或者Getter方法,那么synthesize就不会生成标准的setter或者Getter方法

3.xcode4.5环境以后,可以省略.m文件中的@synthesize,编译器会默认访问_age这个成员变量,如果找不到会在内部自动生成一个私有_age


property和synthesize

原文:http://blog.csdn.net/cooljune/article/details/18839987

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!