In iPhone applications, nstimer is a common class. However, nstimer is also a troublesome class. Here we will talk about some of its usage experiences.
First, let's take a look at how to use nstimer.
The basic usage is as follows:Code(For specific understanding, check the official documentation ):
For rootviewcontroller. H files
# Import <uikit/uikit. h>
@ Interface rootviewcontroller: uitableviewcontroller {
Nstmer * timer;
}
-(Void) TTT :( nstimer *) thetimer;
@ End
For the rootviewcontroller. M file
# Import "rootviewcontroller. H"
@ Implementation rootviewcontroller
# Pragma mark-
# Pragma mark view Lifecycle
-(Void) viewdidload {
[Super viewdidload];
Timer = [nstimer scheduledtimerwithtimeinterval: 10 target: Self selector: @ selector (TTT :) userinfo: Nil repeats: Yes];
// Uncomment the following line to display an edit button in the navigation bar for this view controller.
// Self. navigationitem. rightbarbuttonitem = self. editbuttonitem;
}
-(Void) TTT :( nstimer *) thetimer {
// Your operate
}
-(Void) dealloc {
[Timer invalidate];
[Super dealloc];
}
The basic usage is that simple. Of course, we can also avoid loop execution. However, it should be noted that we should adopt the following method to disable timer as defined above:
If ([Timer isvalid]) {
[Timer invalidate];
}
This is right for us.ProgramMore secure. Let's look at a question. Change the content in dealloc to the following content. Run
-(Void) dealloc {
Nslog (@ "dealloc: % @", [[self class] description]);
Nslog (@ "***** timer retaincount: % d *****", [Timer retaincount]);
[Timer invalidate];
Nslog (@ "***** timer retaincount: % d *****", [Timer retaincount]);
[Super dealloc];
}
Run the program and check the terminal output information. How can the delloc function not be executed? In fact, there is nothing strange. Because our timer has not stopped. So we modify the program as follows. That is, an exit function is added to the function.
-(Ibaction) backbtn :( ID) sender {
Nslog (@ "***** timer retaincount: % d *****", [Timer retaincount]);
[Timer invalidate];
Nslog (@ "***** timer retaincount: % d *****", [Timer retaincount]);
[Self. navigationcontroller popviewcontrolleranimated: Yes];
}
Change delloc:
-(Void) dealloc {
Nslog (@ "dealloc: % @", [[self class] description]);
[Super dealloc];
}
In the next run, you can see that delloc is executed.
The purpose of this process is to ensure that the memory is released when the page is exited; otherwise, the memory will crash (this is especially important for collections ).