//// main.m// 文件管理练习(每秒写入一个时间到文件)//// Created by on 14-10-18.// Copyright (c) 2014年. All rights reserved.//#import#import "WriteDate.h"int main(int argc, const char * argv[]) { @autoreleasepool { WriteDate *writeDate = [[WriteDate alloc] init]; [writeDate runDate]; } [[NSRunLoop currentRunLoop] run]; return 0;}
//// WriteDate.h// 文件管理练习(每秒写入一个时间到文件)//// Created by on 14-10-18.// Copyright (c) 2014年 . All rights reserved.//#import@interface WriteDate : NSObject- (void) runDate;- (void) timerAction:(NSTimer *)timer;@end
//// WriteDate.m// 文件管理练习(每秒写入一个时间到文件)//// Created by on 14-10-18.// Copyright (c) 2014年 . All rights reserved.//#import "WriteDate.h"@implementation WriteDate- (void) runDate { NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *homePath = NSHomeDirectory(); NSString *filePath = [homePath stringByAppendingPathComponent:@"Desktop/test.txt"]; BOOL success = [fileManager createFileAtPath:filePath contents:nil attributes:nil]; if (!success) { NSLog(@"文件创建失败!"); } // 不要将创建对象的方法写入到timerAction中,没必要每次都创建一个对象// 这里还可以优化一下将格式化的工作写在WriteDate中 NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath]; // 这里将fileHandle对象传到timerAction中,避免在timerAction中重复的创建对象 [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 *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"yyyy/MM/dd HH:mm:ss"]; NSString *dateString = [dateFormat stringFromDate:nowDate]; dateString = [dateString stringByAppendingString:@"\n"]; NSData *data = [dateString dataUsingEncoding:NSUTF8StringEncoding]; [fileHandle writeData:data]; if (n == 10) {// 关闭定时器 [timer invalidate]; [fileHandle closeFile]; NSLog(@"程序已退出"); exit(1); } n++;}@end