NSTimer定时器的简单用法/NSTimer Instance

NSTimer定时器的简单用法

版本信息:

OS version : 10.10

Interface Name: NSTimer

Location : Frameworks/Foundation/NSTimer.h


OC源码:


#import <Foundation/NSObject.h>

#import <Foundation/NSDate.h>


@interface NSTimer :NSObject

//类方法

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;



今天只关注上面的这个类方法,这个类方法很实用滴,(打印日志文件,纪录用户操作等等)。

以打印日志文件为例,需要用到3个文件:

Log.h

#import <Foundation/Foundation.h>

@interface Log : NSObject

- (void) Log;//for log

- (void) timerAction:(NSTimer *)timer;


@end


Log.m

#import "Log.h"

@implementation Log
- (void)Log
{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = NSHomeDirectory();
    NSString *filePath = [path stringByAppendingString:@"/IOS/Log.txt"];//create a txt file for log
    BOOL success = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    if (success) {
        NSLog(@"create success");
    }
    //NSFileHandle for handle the txt file
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:fileHandle repeats:YES];
    //NSTimer定时器使用,每一秒call一次timerAction,写入当前时间到txt file 里面
}
- (void) timerAction:(NSTimer *)timer
{
    static int i = 0;
    
    NSFileHandle *fileHandle = timer.userInfo;
    [fileHandle seekToEndOfFile];
    
    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormate = [[NSDateFormatter alloc] init];
    [dateFormate setDateFormat:@" --- yyyy/MM/dd HH:mm:ss"];
    NSString *dateNowString = [dateFormate stringFromDate:now];
    dateNowString = [dateNowString stringByAppendingString:@"\n"];
    NSData *data = [dateNowString dataUsingEncoding:NSUTF8StringEncoding];
    [fileHandle writeData:data];
    
    if (i == 10) {
        [timer invalidate];
        [fileHandle closeFile];
    }
    i++;
}

@end


main.m

#import <Foundation/Foundation.h>
#import "Log.h"


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...

        Log *write = [[Log alloc] init];
        [write log];
        
    }
    [[NSRunLoop currentRunLoop] run];//NSTImer 和 NSRunLoop 配合使用
    return 0;
}







  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值