使用property会自动生成get与set方法。
@interface Time : NSObject
//property会自动生成set与get方法
@property int hour;
@property int minute;
@property int second;
-(void)show;
@end
@implementation Time
-(void)show
{
NSLog(@"%02i:%02i:%02i",_hour,_minute,_second);
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Time *tm=[[Time alloc]init];
tm.hour=23;
tm.minute=12;
tm.second=34;
[tm show];
}
再次修改set方法
@implementation Time
//自定义hour
-(void)setHour:(int)hour
{
if (hour>24 || hour<0) {
//self.hour=0;此处不能使用self.语法,会造成死循环,set->self->set
_hour=0;
}
_hour=hour;
}
-(void)show
{
NSLog(@"%02i:%02i:%02i",_hour,_minute,_second);
}
@end
再进行修改加上synthesize关键字
#import <Foundation/Foundation.h>
@interface Time : NSObject
{
//不会自动生成get与set
int _hour;
int _minute;
int _second;
}
//property会自动生成set与get方法
@property int hour;
@property int minute;
@property int second;
-(void)show;
@end
#import "Time.h"
@interface Time()
@end
@implementation Time
//实现自动生成
@synthesize hour;
@synthesize minute;
@synthesize second;
-(void)show
{
NSLog(@"%02i:%02i:%02i",_hour,_minute,_second);
}
@end
上面打印结果如下
那为何会打印输出的全部是0呢?原因就是synthesize会在成员变量中寻找hour,minute,second但是成员变量中只有_hour,_minute,_second。所以找不到,就会自动生成hour,minute,second成员变量。最后打印的是没有经过赋值的_hour等成员变量,就为0。
最后修改方法如下。