OC开发系列-@property和@synthesize

时间:2023-03-09 03:00:19
OC开发系列-@property和@synthesize

property和synthesize

创建一个Person类。提供成员属性的_age和_height的setter和getter方法。

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
int _age;
int _height;
} - (void)setAge:(int)age;
- (int)age;
@end #import "Person.h"
@implementation Person - (void)setAge:(int)age
{
_age = age;
}
- (int)age
{
return _age;
}
@end

开发中考虑封装性将成员属性通过提供setter与getter结构供外界访问。但是这些setter跟getter代码没有任何技术含量。于是苹果提供关键字propertysynthesize 关键字利用编译器特性将我们自动生成setter跟getter方法。

@property int age;
// - (void)setAge:(int)age;
// - (int)age; @synthesize age;
/*
- (void)setAge:(int)age
{ }
- (int)age
{ }
*/

@synthesize age虽然帮我们实现了set跟get方法的实现,并未指定将外界传递的值对哪个成员属性进行赋值。如上Person类需要给成员_age复制。

@synthesize age = _age;

如果我们使用@synthesize age没有指定给哪个成员复制,那么会自动访问与@synthesize后面同名的成员属性,如果没有同名的成员属性也会自动生成同名私有成员变量

通过@property 和@synthesize我们可以对Person类简写成如下

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
int _age;
int _height;
} @property int age;
@property int height;
@end #import "Person.h"
@implementation Person @synthesize age = _age;
@synthesize height = _height;
@end

上面的Person类还可以继续进行简写,不写成员变量。xcode编译器自动生成带有下划线的私有成员变量。这是由于Xcode的功能强大。

#import <Foundation/Foundation.h>
@interface Person : NSObject @property int age;
@property int height;
@end #import "Person.h"
@implementation Person @synthesize age = _age;
@synthesize height = _height;
@end

Xcode4.4之后property关键字可以独揽@synthesize的功能。因此Person类可以简写:

#import <Foundation/Foundation.h>
@interface Person : NSObject @property int age;
@property int height;
@end #import "Person.h"
@implementation Person @end

自动生成的下划线成员属性特点:

* 自动生成下划线的成员属性是私有的,子类是不可以直接访问的

* 如果手动生成_成员属性,系统则不会帮我们生成

* 如果手动同时重写setter跟getter实现,xcode不会帮我们生成下划线属性