在声明一个变量的时候,经常有使用下面的三种形式:

@interface testView : UIView

{

//1、内部变量,外部不能访问

UIButton *button1;

//3、声明变量,同时声明了一个同名变量属性

UIButton *button3;

}


//2、声明一个属性,从Xcode4.5开始,使用@property关键字将自动生成setter和getter方法,不用@synthesize关键字

@property (nonatomic, strong) UIButton *button2;

//

@property (nonatomic, strong) UIButton *button3;


@end

第一种方式声明的变量是一个内部变量,只能在该类中被访问,在类的外部是不能访问的。因此,这样的变量最好不要在.h文件中去声明,应该放在.m文件中。

第二种方式声明了一个属性,从Xcode 4.5以后,不用使用@synthesize关键字就自动生成了该属性的setter和getter方法。

第三种方法是在声明一个变量的时候,同时声明了一个与变量同名的属性。这时候,如果不使用@synthesize关键字,会产生一个警告信息。

这种情况让我很迷惑,通过写了一个简单的demo测试了一番,现在将我的分析结果总结一下。

先上代码:

@synthesize button3 = _button3;


- (id)initWithFrame:(CGRect)frame

{

self = [super initWithFrame:frame];

if (self) {

// Initialization code

//button1

button1 = [[UIButton alloc] initWithFrame:CGRectMake(20, 10, 75, 44)];

button1.backgroundColor = [UIColor redColor];

[button1 setTitle:@"button1" forState:UIControlStateNormal];

[self addSubview:button1];

//button2

_button2 = [[UIButton alloc] initWithFrame:CGRectMake(20, 64, 75, 44)];

_button2.backgroundColor = [UIColor greenColor];

[_button2 setTitle:@"button2" forState:UIControlStateNormal];

[self addSubview:_button2];

//button3

button3 = [[UIButton alloc] initWithFrame:CGRectMake(20, 118, 75, 44)];

button3.backgroundColor = [UIColor blueColor];

[button3 setTitle:@"button3" forState:UIControlStateNormal];

[self addSubview:button3];

_button3.backgroundColor = [UIColor grayColor];

[_button3 setTitle:@"button3_1" forState:UIControlStateNormal];

_button3 = [[UIButton alloc] initWithFrame:CGRectMake(20, 172, 75, 44)];

_button3.backgroundColor = [UIColor grayColor];

[_button3 setTitle:@"button3_1" forState:UIControlStateNormal];

[self addSubview:_button3];

}

return self;

}

通过@synthesize关键字我先把警告信息屏蔽掉了,button1是一个供内部访问的变量,button2是可供外部访问的,这都没什么,重点是button3。

通过代码可以发现,我分别对button3和_button3进行了初始化,并设置了button的title和背景颜色。在对button3初始化完成后,我希望能通过_button3去修改button3的背景颜色和title。实际运行效果如下图:

_button3对button3的修改无效!为什么这样?我的理解是button3是供内部访问的变量,_button3是一个可供外部访问的属性,即使我通过@synthesize button3 = _button3进行设置,也是对@property (nonatomic, strong) UIButton *button的设置。因此我得出结论:button3和_button3是完全独立的,第三种声明方式是无意义的。

接着测试,我在另外一个文件中引入我的测试文件,并实例化了一个对象希望对button们进行访问,上代码:

- (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

testView *view = [[testView alloc] initWithFrame:CGRectMake(10, 50, 300, 250)];

[view.button2 setTitle:@"按钮2" forState:UIControlStateNormal];

[view.button3 setTitle:@"按钮3" forState:UIControlStateNormal];

[self.view addSubview:view];

}

运行效果如图:

通过测试分析最终得出的结论如下:

1、声明一个内部使用变量,在.m文件中声明即可。(使用@interface { }或@property均可)。

2、声明一个可供外部访问的属性,在.h文件中使用@property即可。



PS:第一次原创写blog,才发现写东西这么难啊!

理解不一定对,希望大家轻喷,多指点!