创建一个Date.text文件,获取当前的日期,将日期格式为“2013/02/14 05:20:00”的形式。然后一秒钟记录一次,将新的时间存入到文件中。

打开xcode 


点击  create  a  new  xcode  project


点击  左侧  Application  选择右侧中的 Command Line  Tool(相当于windows下的command)


         ---  next


  product Name:NSFileHandleTask1
  
  Company identifier:com.imti


  type: foundation  是一个framework




  取消选择 use Automatic  Reference  Counting




        ---  next




        ---  create






new  file...    


           name:WriteDate
           subclass:  NSObject






WriteDate.h


加入


- (void)runWrite;




WriteDate.m


加入




- (void)runWrite {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = NSHomeDirectory();
    NSString *filePath = [path stringByAppendingPathComponent:@"Date.text"];
    //创建文件
    BOOL success = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    if (success) {
        NSLog(@"create success");
    }
    
    //写文件对象
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];


    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:fileHandle repeats:YES];
}


- (void)timerAction:(NSTimer *)timer {
    static int n = 0;
    
    NSFileHandle *fileHandle = timer.userInfo;
    //跳到文件的末尾
    [fileHandle seekToEndOfFile];
    
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *dateformate = [[NSDateFormatter alloc] init];
    //设置日期的格式
    [dateformate setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    //将日期对象格式为字符串
    NSString *datestring = [dateformate stringFromDate:nowDate];
    [dateformate release];
    
    datestring = [datestring stringByAppendingString:@"\n"];
    NSData *data = [datestring dataUsingEncoding:NSUTF8StringEncoding];
    [fileHandle writeData:data];
    
    if (n == 10) {
        [timer invalidate];//停止定时器
        //关闭文件
        [fileHandle closeFile];//关闭管道
    }
    
    n++;
}






时间定时器 NSTimer 一个能够定时的完成任务的类


说明:


scheduledTimerWithTimeInterval:(NSTimeInterval)seconds  


预订一个Timer,设置一个时间间隔。


表示输入一个时间间隔对象,以秒为单位,一个>0的浮点类型的值,如果该值<0,系统会默认为0.1


 target:(id)aTarget


表示发送的对象,如self


 selector:(SEL)aSelector


方法选择器,在时间间隔内,选择调用一个实例方法


userInfo:(id)userInfo


此参数可以为nil,当定时器失效时,由你指定的对象保留和释放该定时器。


repeats:(BOOL)yesOrNo


当YES时,定时器会不断循环直至失效或被释放,当NO时,定时器会循环发送一次就失效。






timer开始
[tm fier];
 
timer停止:
[tm invalidate];
 
timer是否已经开始在进行中:
BOOL b = [tm isValid];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值