标签:
这是一个人定闹钟的例子,就是人委托闹钟叫醒自己
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
标签:
原文地址:http://my.oschina.net/u/2366900/blog/425041