Main code:
1 set a timer first2 timeinterval: Set time interval3 target: Represents the Sent object4 selector: Select an instance method5 userInfo: This parameter can be nil, and when the timer fails, the timer is reserved and freed by the object you specify6 7[Nstimer Scheduledtimerwithtimeinterval:2.0ftarget:self selector: @selector (dotimer:) userinfo:handle Repeats:yes];8 9 Ten- (void) Dotimer: (Nstimer *) Timer One { A ... - //Timer Failure - [timer invalidate]; the - } - - + - Main function + A [Timer startwrite]; at //When added to Runloop, the timer is automatically triggered after the timeinterval seconds specified at initialization. -[[Nsrunloop Currentrunloop]run];
Full code:
1 main.m2 3 4Timers *timer =[[Timers Alloc]init];5 6 [Timer startwrite];7 8 [[Nsrunloop Currentrunloop]run];9 Ten Timer.h One #import<Foundation/Foundation.h> A - @interfaceTimers:nsobject - the@property (nonatomic,retain) Nstimer *timer; - -- (void) Startwrite; - + @end - + A #import "Timers.h" at - @implementationTimers - - Static intnum =0; - - in- (void) Dotimer: (Nstimer *) Timer - { to //dealing with problems +num++; -Nsfilehandle *handle =[Timer userInfo]; theNSDate *date =[NSDate Date]; * //Set Date format $NSDateFormatter *formatter =[[NSDateFormatter alloc]init];Panax Notoginseng[Formatter Setamsymbol:@"Morning"]; -[Formatter Setpmsymbol:@"Afternoon"]; the[Formatter Setdateformat:@"yyyy mm month DD Day HH:MM:SS EEE AAA"]; + A //date Formatting theNSString *time =[Formatter stringfromdate:date]; + //Add line break -NSString *time1 = [Time stringbyappendingstring:@"\ n"]; $ $NSData *data =[time1 datausingencoding:nsutf8stringencoding]; - //move cursor to end of file - [handle seektoendoffile]; the //Write Data - [handle writedata:data];Wuyi the if(num>=5) - { Wu [timer invalidate]; -NSLog (@"ha ha haha"); About //[handle closefile]; $ } - } - -- (void) Startwrite A { + //Data Store Path theNSString *path =@"/users/scjy/desktop/Liu Jirong Practice/oc/Exercise 1/Date Write/date write/dateinsert.txt"; - $Nsfilemanager *filemanger =[Nsfilemanager Defaultmanager]; the if(![Filemanger Fileexistsatpath:path]) the { the //If the file does not exist, create the file the [Filemanger createfileatpath:path contents:nil Attributes:nil]; - in } the the //Prepare to write AboutNsfilehandle *handle =[Nsfilehandle Filehandleforwritingatpath:path]; the the[Nstimer Scheduledtimerwithtimeinterval:2.0ftarget:self selector: @selector (dotimer:) userinfo:handle Repeats:yes]; the + } - @end
Object-c's Timer