ios - 堆内存的持久化分配 NSTimer

标签 ios objective-c memory-management nstimer nsrunloop

我发现示例项目存在问题。我只是创建一个 scheduledTimer 来“激活”标签,然后,当我达到我想要的结果时,我使计时器无效并设置另一个计时器,这次作为“时钟”。 这是我使用的代码

//
//  ViewController.m
//  
//
//  
//  
//

#import "ViewController.h"

#define ANIMATION_INTERVAL              0.07 // in secondi
#define ANIMATION_DURATION              1   // in secondi

@interface ViewController ()
{
    int contatore;
    NSString *hour;
    NSString *minute;
    NSString *second;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    contatore = 0;

    [self startTimeAnimation];


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)startTimeAnimation
{
    NSTimer * animationTimer = [NSTimer scheduledTimerWithTimeInterval:ANIMATION_INTERVAL target:self selector:@selector(timeout:) userInfo:nil repeats:YES];
}

-(void)timeout: (NSTimer *)timer
{
    // Simulate of the Timer Duration with a counter
    if (contatore < ceilf(ANIMATION_DURATION/ANIMATION_INTERVAL))
    {
        // Proceed with animation
        contatore++;

        int tempHour = arc4random_uniform(24);
        int tempMinute = arc4random_uniform(60);
        int tempSecond = arc4random_uniform(60);

        if (tempHour < 10)
        {
            hour = [NSString stringWithFormat:@"0%d", tempHour];
        }
        else
        {
            hour = [NSString stringWithFormat:@"%d", tempHour];
        }

        if (tempMinute < 10)
        {
            minute = [NSString stringWithFormat:@"0%d", tempMinute];
        }
        else
        {
            minute = [NSString stringWithFormat:@"%d", tempMinute];
        }

        if (tempSecond < 10)
        {
            second = [NSString stringWithFormat:@"0%d", tempSecond];
        }
        else
        {
            second = [NSString stringWithFormat:@"%d", tempSecond];
        }

        _orarioLbl.text = [NSString stringWithFormat:@"%@:%@:%@", hour, minute, second];
    }
    else
    {
        // Stops animation
        [timer invalidate];
        [timer release];
        contatore = 0;



        [self setActualTime];


        // Starts clock
        NSTimer *clockTimer = [NSTimer timerWithTimeInterval:.5f target:self selector:@selector(updateClock) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:clockTimer forMode:NSRunLoopCommonModes];
    }
}

-(void)updateClock
{
    [self setActualTime];
}


-(void)setActualTime
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"HH"];
    hour = [dateFormatter stringFromDate:[NSDate date]];

    [dateFormatter setDateFormat:@"mm"];
    minute = [dateFormatter stringFromDate:[NSDate date]];

    [dateFormatter setDateFormat:@"ss"];
    second = [dateFormatter stringFromDate:[NSDate date]];

    _orarioLbl.text = [NSString stringWithFormat:@"%@:%@:%@", hour, minute, second];
    [dateFormatter release];
}

@end

自从我启动“时钟”以来,内存仍然保持在 19/20 MB,并且持续分配。当计时器更新分钟值时,持久分配会增加,如您在 gif 中所见!这怎么可能?然而,19MB 的内存对于一个简单的时钟来说也太多了,不是吗? 在 Instruments 上进行分析,新分配都是关于 CoreGraphics 的!

animated gif Instruments

编辑 我在另一台设备上对其进行了测试,持久分配减少了。我不知道为什么,但我是这样解决的。谢谢

最佳答案

NSTimer 保留其目标,这可能会导致保留周期。获取对 self 的弱引用并将其设置为目标:

__weak typeof(self) weakSelf = self;
NSTimer * animationTimer = [NSTimer scheduledTimerWithTimeInterval:ANIMATION_INTERVAL target:weakSelf selector:@selector(timeout:) userInfo:nil repeats:YES];

__weak typeof(self) weakSelf = self;
NSTimer *clockTimer = [NSTimer timerWithTimeInterval:.5f target:weakSelf selector:@selector(updateClock) userInfo:nil repeats:YES];

我还可以建议您为 dateFormatter 创建一个属性,因为创建 NSDateFormatter 的成本很高。为什么要发布 dateFormatter?您没有使用 ARC 吗?

关于ios - 堆内存的持久化分配 NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26733467/

相关文章:

android - 设备显示设置(Android 屏幕缩放和字体)

iOS Sqlite NSDate 值

ios - 我应该在哪里释放组队列?

ios - 当用户点击 View Controller 时如何使 SWRevealViewController 菜单消失

ios - 如何在 UIScrollView 的特定 subview 中禁用滚动

ios - 配置 iOS VoIP 应用程序以在 sleep /后台模式下运行

iphone - 强制核心位置使用 gps

objective-c - 如何使用 pdfkit ios 11 打开 pdf 文件?

c - 使用双指针为结构内的动态结构数组分配内存**

c - 现代处理器上的内存对齐?