【OC学习-24】实例:创建一个文件并连续写入10次当前时间——巩固文件操作和熟悉定时器操作

来源:互联网 发布:淘宝上付费引流的软件 编辑:程序博客网 时间:2024/06/04 04:15

(1)创建一个writeData类,在writeData.h里面:

#import <Foundation/Foundation.h>@interface writeData : NSObject-(void)runWrite;//定义一个方法供调用,这个方法是创建并打开一个文件,然后利用定时器每个1秒调用另一个私有方法,这私有方法把当前时间到这个文件夹,但只写10次@end

(2)在writeData.m里面具体实现功能:

#import "writeData.h"@implementation writeData-(void)runWrite{    //以下两行生成一个文件目录    NSString *homePath=NSHomeDirectory();    NSString *filePath=[homePath stringByAppendingPathComponent:@"testfile.text"];    //用上面的目录创建这个文件    NSFileManager *fileManager=[NSFileManager defaultManager];    BOOL success=[fileManager createFileAtPath:filePath contents:nil attributes:nil];    if (success) {        NSLog(@"success");    }    //打开上面创建的那个文件    NSFileHandle *fileHandle=[NSFileHandle fileHandleForWritingAtPath:filePath];    //开启定时器,每隔1s调用一个timeAction方法    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction:) userInfo:fileHandle repeats:YES];}-(void)timeAction:(NSTimer *)timer{    static int n=0;    NSFileHandle *fileHandle=timer.userInfo;//通过timer把对象传过来,只不过取了个重复的名字,可以换名字,但下面用到的几个地方要跟着变换    [fileHandle seekToEndOfFile];//因为是循环写入,所以每次打开文件因为把光标定位在文末    NSDate *currDate=[NSDate date];//先获取当前时间    //以下两行是创建一个格式化工具,先初始化一个时间格式,然后定义这个格式    NSDateFormatter *dateFormate=[[NSDateFormatter alloc]init];    [dateFormate setDateFormat:@"yyyy/MM/dd HH:mm:ss"];    //利用上面的时间格式工具把日期转换成字符串对象格式    NSString *dateStr=[dateFormate stringFromDate:currDate];    dateStr=[dateStr stringByAppendingString:@"\n"];//并且在这个字符串后面增加换行    NSData *data=[dateStr dataUsingEncoding:NSUTF8StringEncoding];//把这个字符串转换成数据格式用于写入文件里    [fileHandle writeData:data];//写入文件    if (n==10) {     //控制写入次数        [timer invalidate];//达到次数后关闭定时器        [fileHandle closeFile];//关闭文件    }    n++;}@end

(3)在main.m里:

#import <Foundation/Foundation.h>#import "writeData.h"//别忘记导入int main(int argc, const char * argv[]){    @autoreleasepool {        writeData *wdata=[[writeData alloc]init];//声明一个对象        [wdata runWrite];//利用这个对象去调用方法    }    [[NSRunLoop currentRunLoop]run];//启动加入到消息中的定时器吧应该,如果不写这句,只创建了这个文件,但是没有任何写入数据    return 0;}

(4)结果


总结:动手写,有些语句不太理解,百度,并且在后面继续巩固。

更多NSTimer详见:NSTimer

更多NSRunLoop详见:NSRunLoop的一点理解       IOS开发中NSRunloop跟NSTimer的问题    NSRunLoop 概述和原理

0 0
原创粉丝点击