【非凡程序員】 OC第十四節課 (代理模式 二 鬧鈴響了)

這是一我的定鬧鐘的例子,就是人委託鬧鐘叫醒本身dom

main函數:函數

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

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;ui

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

       
    }
    return 0;
}spa

Person.h文件.net

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

@interface  Person : NSObjectorm

@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;get

@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

相關文章
相關標籤/搜索