现在的位置: 首页 > 综合 > 正文

iPhone应用中关于NSTimer的一些问题

2013年09月17日 ⁄ 综合 ⁄ 共 1666字 ⁄ 字号 评论关闭

在iphone应用中,NSTimer是一个比较常用的类。但NSTimer也是一个比较麻烦的类。这里就谈谈关于它的一点使用心得。

 

首先我们来看看NSTimer的使用方法。

基本使用方法下面就用代码来说明了(至于具体的理解自己去查官方文档吧):

 

对RootViewController.h文件

#import <UIKit/UIKit.h>
@interface RootViewController : UITableViewController {
    NSTimer *timer;
}

-(void)ttt:(NSTimer *)theTimer;

@end

 

对RootViewController.m文件

#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];
}
基本用法就是这么简单了。当然我们也可以不让其循环执行。不过这里要说明一点,对于上面定义的timer我们最好采用如下的方式来对其进行判断式关闭:

if ([timer isValid]) {
        [timer invalidate];
}

这样有对我们的程序更加安全。我们看一个问题。我们把dealloc中的内容改为如下的内容。运行

- (void)dealloc {
    NSLog(@"dealloc : %@",[[self class] description]);
    NSLog(@"****timer retainCount : %d****",[timer retainCount]);
    [timer invalidate];
    NSLog(@"****timer retainCount : %d****",[timer retainCount]);
    [super dealloc];
}

运行程序,看终端输出信息,怎么delloc函数没有执行呢?其实没什么奇怪的。因为我们的timer还没有停止嘛。这个所以我们把程序修改如下。即在函数中增加了一个退出函数

-(IBAction)backBTN:(id)sender {
    NSLog(@"****timer retainCount : %d****",[timer retainCount]);
    [timer invalidate];
    NSLog(@"****timer retainCount : %d****",[timer retainCount]);
    [self.navigationController popViewControllerAnimated:YES];
}

把delloc改为:

- (void)dealloc {

    NSLog(@"dealloc : %@",[[self class] description]);

    [super dealloc];

}

在次运行嘿,看到delloc执行了哇。

之所以这样处理的目的在于保证在退出此页面时处理内存释放的问题,否则会导致内存崩溃(这对做集合特别重要)。

 

 

 

抱歉!评论已关闭.