您的位置:首页 > 其它

OC-文件和计时器操作实例

2014-08-22 10:54 316 查看
Example:创建一个Date.text文件,获取当前的日期,将日期存储为格式”2014/08/22 10:25:23“的形式。然后一秒钟记录一次,将新的时间存入到文件中。

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(@"created 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];

dateString = [dateString stringByAppendingString:@"\n"];

NSData *data = [dateString dataUsingEncoding:NSUTF8StringEncoding];

[fileHandle writeData:data];

if (n == 10) {

[timer invalidate];

[fileHandle closeFile];

}

n++;

}

main函数的内容:

int main(int argc,const char * argv[ ])

{

@autoreleasepool {

WriteDate *writeDate = [[WriteDate alloc]init];

[writeDate runWrite];

}

[[NSRunLoop currentRunLoop] run];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: