码迷,mamicode.com
首页 > 其他好文 > 详细

【非凡程序员】 OC第十四节课 (代理模式 二 闹铃响了)

时间:2015-06-04 22:56:39      阅读:305      评论:0      收藏:0      [点我收藏+]

标签:

这是一个人定闹钟的例子,就是人委托闹钟叫醒自己

main函数:

#import <Foundation/Foundation.h>
#import "Person.h"
#import "Clock.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool  {
        // insert code here...
        NSLog(@"Hello, World!");
       
        Person *person1=[[Person alloc]init];
        person1.name=@"岁平";
       
        Clock *clock=[[Clock alloc]init];
        clock.person =person1;
   
        person1.delegate=clock;

        person1.persondate=@"201506041716";
        
        [person1 setup];
       
        [[NSRunLoop currentRunLoop]run];

       
    }
    return 0;
}

Person.h文件

#import <Foundation/Foundation.h>
#import "ClockProtocol.h"

@interface  Person : NSObject

@property (nonatomic,assign) NSString *name;
@property (nonatomic,assign) id <ClockProtocol> delegate;
@property (nonatomic,assign) int count;
@property (nonatomic,assign) int suijishu;
@property (nonatomic,assign) NSString *persondate;
-(void) setup;
-(void) getup:(int) ringTimes;

@end

Person.m文件:

#import "Person.h"

@implementation Person

-(id)init
{
    self =[super init];
    if (self)
    {
        _suijishu=arc4random() %10;
    }
    return self;
}

-(void) setup
{
    NSLog(@"%@设置---?",_name);
 
    [_delegate ring];
}


-(void) getup:(int) ringTimes

{
    if (_suijishu==ringTimes)
    {
        NSLog(@"我要起来了");
        //[_delegate stop];
    }
    else
    {
        NSLog(@"getup.....");
    }

}

@end

Clock.h文件:

#import <Foundation/Foundation.h>
#import "ClockProtocol.h"
@class  Person;

@interface Clock : NSObject<ClockProtocol>
@property (nonatomic,assign) int count;
@property (nonatomic,assign) NSTimer *timer;
@property (nonatomic,weak) Person *person;
-(void) ring;

@end

Clock.m文件:

#import "Clock.h"
#import "Person.h"

@implementation Clock

-(id) init
{
    self = [super init];
 
    if (self!=nil)
    {
        _timer=[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(ring) userInfo:nil repeats:YES];
    }
    return self;
}


-(void) ring

{
    NSDate *date=[NSDate date];
    NSDateFormatter *f=[NSDateFormatter new];
    [f setDateFormat:@"yyyyMMddHHmm"];
    NSString *datetime=[f stringFromDate:date];
 
    if ([datetime isEqualToString: _person.persondate])
    {
        _count++;
       
        [_person getup:_count];
  
        [self sing];
       
    }
    else
    {
        NSLog(@"%@,datetime);
    }
   
 
}

-(void) sing
{
    NSLog(@"ding----ding---ding   快起床啊啊啊-------");
}

- (void) stop
{
    [_timer invalidate];
}

@end

ClockProtocol.h文件(协议)

#import <Foundation/Foundation.h>

@protocol ClockProtocol <NSObject>

@optional
-(void) ring;

@required
-(void) stop;

@end

【非凡程序员】 OC第十四节课 (代理模式 二 闹铃响了)

标签:

原文地址:http://my.oschina.net/u/2366900/blog/425041

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!