#import "ViewController.h"
#import "Hero.h"
@interface ViewController ()
@property(nonatomic,strong)Hero *hero;
@property(nonatomic,strong)UIView *view1;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_hero = [[Hero alloc] init];
_hero.blood = 300;
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(bloodLess) userInfo:nil repeats:YES];
[_hero addObserver:self forKeyPath:@"blood" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
NSString *newBlood = [change objectForKey:@"new"];
if ([newBlood integerValue] <= 50) {
_hero.blood = 300;
}
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[_hero removeObserver:self forKeyPath:@"blood"];
}
-(void)bloodLess
{
[_view1 removeFromSuperview];
_view1 = [[UIView alloc] initWithFrame:CGRectMake(10, 100, _hero.blood, 50)];
_view1.backgroundColor = [UIColor redColor];
[self.view addSubview:_view1];
_hero.blood -= 50;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end