NSTimer定时器的简单用法/NSTimer Instance
来源:互联网 发布:淘宝 宝贝分类 编辑:程序博客网 时间:2024/03/29 22:25
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
#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;}
0 0
- NSTimer定时器的简单用法/NSTimer Instance
- 定时器NSTimer的简单使用
- 简单NSTimer 定时器
- 定时器NSTimer的简单使用和停止
- NSTimer 定时器的使用
- NSTimer(定时器)的使用
- NSTimer定时器的使用
- NSTimer 定时器的应用
- NSTimer定时器的使用
- NSTimer 简单用法
- NSTimer简单用法
- IOS NSTimer 定时器用法总结
- IOS NSTimer 定时器用法总结
- IOS NSTimer 定时器用法总结
- NSTimer 定时器
- NSTimer 定时器
- NSTimer 定时器
- NSTimer定时器
- JavaBean的编译和部署说明
- 【Python】Learn Python the hard way, ex4 使用变量
- 利用MSSQL复制功能实现与Oracle数据库同步
- ns-2与TCP拥塞模拟 之六 ns-2 TCP拥塞控制核心模块-变量说明
- Unix编程学习笔记---文件系统与 i节点
- NSTimer定时器的简单用法/NSTimer Instance
- 由scroll view引发的一系列小零碎
- theano tutorial学习笔记(一)
- Logistic Regression笔记
- CTreeCtrl带CHECKBOX属性,实现联动效果(点击父节点全部子节点被选中)
- 网络爬虫Python试验
- UINavigationBar自定义返回按钮
- Set Matrix Zeroes
- Java基础知识学习