//
// WriteDate.m
// NSFIleHandleTask1
//
// Created by New-World on 13-11-3.
// Copyright (c) 2013年 Gary. All rights reserved.
//
#import "WriteDate.h"
@implementation WriteDate
-(void)runWrite
{
NSFileManager *fileManger=[NSFileManager defaultManager];
NSString *path=NSHomeDirectory();
NSString *filepath=[path stringByAppendingPathComponent:@"Date.text"];//文件路径
BOOL success =[fileManger createFileAtPath:filepath contents:nil attributes:nil];
if (success) {
NSLog(@"Date文件创建成功");
}
NSFileHandle *fileHandle=[NSFileHandle fileHandleForWritingAtPath:filepath];//创建一个写入数据的fileHandle对象
NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self
selector:@selector(timerAction:) userInfo:fileHandle repeats:YES];//创建一个timer对象,每隔一秒钟写入一条数据
[timer fire];//启动timer
}
-(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];//按格式字符串格式化获取的时间
NSLog(@"%@",datestring);
datestring=[datestring stringByAppendingString:@"\n"];//添加一个换行符
NSData *data=[datestring dataUsingEncoding:NSUTF8StringEncoding];
[fileHandle writeData:data];
if (n==10) {
[timer invalidate];//设置timer无效
[fileHandle closeFile];//关闭fileHandle
}
n++;
}
@end
OC之文件管理写入文件
最新推荐文章于 2022-03-18 17:21:00 发布