object-c之计时器

主要代码:

 1 先设置一个定时器
 2 TimeInterval:设置时间间隔
 3 target:表示发送的对象
 4 selector:选择一个实例方法
 5 userInfo:此参数可以为nil,当定时器失效时,由你指定的对象保留和释放该定时器
 6 
 7 [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(doTimer:) userInfo:handle repeats:YES];
 8 
 9 
10 - (void)doTimer:(NSTimer *)timer
11 {
12 ……
13 // 计时器失效
14 [timer invalidate];
15 
16 }
17 
18 
19 
20 主函数
21 
22 [timer startWrite];
23 //添加到runloop中后,该定时器将在初始化时指定的timeInterval秒后自动触发。
24 [[NSRunLoop currentRunLoop]run];

 

 

完整代码:

 

 1 main.m
 2 
 3         
 4         Timers *timer = [[Timers alloc]init];
 5         
 6         [timer startWrite];
 7         
 8         [[NSRunLoop currentRunLoop]run];
 9 
10 Timer.h
11 #import <Foundation/Foundation.h>
12 
13 @interface Timers : NSObject
14 
15 @property(nonatomic,retain) NSTimer *timer;
16 
17 - (void)startWrite;
18 
19 @end
20 
21 
22 #import "Timers.h"
23 
24 @implementation Timers
25 
26 static int num = 0;
27 
28 
29 - (void)doTimer:(NSTimer *)timer
30 {
31     // 处理问题
32     num++;
33     NSFileHandle *handle = [timer userInfo];
34     NSDate *date = [NSDate date];
35     // 设置日期格式
36     NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
37     [formatter setAMSymbol:@"上午"];
38     [formatter setPMSymbol:@"下午"];
39     [formatter setDateFormat:@"YYYY年MM月dd日 HH:mm:ss EEE aaa"];
40     
41     // 日期格式化
42     NSString *time = [formatter stringFromDate:date];
43     // 添加换行
44     NSString *time1 = [time stringByAppendingString:@"\n"];
45     
46     NSData *data = [time1 dataUsingEncoding:NSUTF8StringEncoding];
47     // 光标移到文件末尾
48     [handle seekToEndOfFile];
49     // 写入数据
50     [handle writeData:data];
51     
52     if (num>=5)
53     {
54         [timer invalidate];
55         NSLog(@"哈哈哈");
56         //    [handle closeFile];
57     }
58 }
59 
60 - (void)startWrite
61 {
62     // 数据存储路径
63     NSString *path = @"/Users/scjy/Desktop/刘二龙练习/OC/练习1/日期写入/日期写入/dateInsert.txt";
64     
65     NSFileManager *filemanger = [NSFileManager defaultManager];
66     if (![filemanger fileExistsAtPath:path])
67     {
68         // 如果文件不存在,创建文件
69         [filemanger createFileAtPath:path contents:nil attributes:nil];
70         
71     }
72     
73     // 准备写入
74     NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:path];
75     
76     [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(doTimer:) userInfo:handle repeats:YES];
77     
78 }
79 @end

 

posted @ 2015-07-20 21:32  凝月霜雪  阅读(447)  评论(0编辑  收藏  举报