【问题标题】:How to deal with leaks in iOS when memory consumption climbs but Leaks does not detect a leak? [closed]当内存消耗攀升但 Leaks 未检测到泄漏时,如何处理 iOS 中的泄漏? [关闭]
【发布时间】:2013-10-21 07:32:08
【问题描述】:

我正在开发一个 iOS ARC 应用程序(可根据要求提供更多代码),之前我正在制作和丢弃大量图像。我认为我在某个地方仍然有对图像的引用,即使我调用 removeFromSuperview 并尝试删除对不再使用的图像的所有引用。我尝试了 Leaks,Leaks 报告内存使用量随着时间的推移大致呈线性增长,从 17M 左右开始。

我检查并将所有对图像的引用替换为实例变量,因此它们将占用少量、有限且固定数量的内存,并转换而不是摆脱用于时钟指针的图像。不幸的是,这导致内存使用量随着时间的推移缓慢增加,从 5M 而不是 17M 开始,但除此之外,同样的问题,只是转换为更好的起点。

我的代码的精简版本如下。您能否告诉我什么是泄漏(或“伪泄漏”,因为泄漏并未表示泄漏)以及如何保持接近代码启动时使用的内存边界?

谢谢,

- (void) renderScreen
{
int height = floor([[UIScreen mainScreen] bounds].size.height + .4);
int width = floor([[UIScreen mainScreen] bounds].size.width + .4);

if (height == 2048 || height == 2008 || height == 1024 || height == 1004 || height == 984)
{
    if (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation))
    {
        _backgroundImage = [UIImage imageNamed:@"Background-Default-Portrait.png"];
    }
    else
    {
        _backgroundImage = [UIImage imageNamed:@"Background-Default-Landscape.png"];
    }
}
else if (height == 1536 || height == 768 || height == 748 || height == 728)
{
    _backgroundImage = [UIImage imageNamed:@"Background-Default-Landscape.png"];
}
else if (height == 1136 || height == 1116 || height == 1096)
{
    if (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation))
    {
        _backgroundImage = [UIImage imageNamed:@"Background-Default-568.png"];
    }
    else
    {
        _backgroundImage = [UIImage imageNamed:@"Background-Default-Rotated-568.png"];
    }
}
else if (height == 960 || height == 940 || height == 920 || height == 480 || height == 460 || height == 440)
{
    if (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation))
    {
        _backgroundImage = [UIImage imageNamed:@"Background-Default.png"];
    }
    else
    {
        _backgroundImage = [UIImage imageNamed:@"Background-Default-Rotated.png"];
    }
}
else if ((height == 640 || height == 620 || height == 600) && (width == 1136 || width == 1116 || width == 1096))
{
    _backgroundImage = [UIImage imageNamed:@"Background-Rotated-568.png"];
}
else if ((height == 640 || height == 620 || height == 600 || height == 320 || height == 300 || height == 280) && (width == 960 || width == 940 || width == 920 || width == 480 || width == 470 || width == 410))
{
    if (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation))
    {
        _backgroundImage = [UIImage imageNamed:@"Background-Default-Portrait.png"];
    }
    else
    {
        _backgroundImage = [UIImage imageNamed:@"Background-Default-Rotated.png"];
    }
}
else
{
    _backgroundImage = [UIImage imageNamed:@"Background-Default-Portrait.png"];

}
if (!UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation))
{
    int juggle = height;
    height = width;
    width = juggle;
}
NSUInteger centerX = width * .5;
NSUInteger centerY = height * .5;

_containerRect = CGRectZero;
_containerRect.size = [[UIScreen mainScreen] bounds].size;

self.view.backgroundColor = [UIColor colorWithPatternImage:_backgroundImage];
_backgroundView = [[UIImageView alloc] initWithImage:_backgroundImage];
[self.view addSubview:_backgroundView];
if (_changed)
{
    _containerView = [[UIView alloc] initWithFrame:_containerRect];
}

double timeStampSeconds = [[NSDate date] timeIntervalSince1970];
double hours   = fmod(timeStampSeconds / 86400, 24);
double minutes = fmod(timeStampSeconds /  3600, 60);
double seconds = fmod(timeStampSeconds,     60);
NSLog(@"Milliseconds: %lf, Hours: %.0f, minutes: %.0f, seconds: %.0f", timeStampSeconds * 1000.0, hours, minutes, seconds);
[_containerView removeFromSuperview];
_containerView = [[UIView alloc] initWithFrame:_containerRect];
_hourHandImage = [UIImage imageNamed:@"hour-hand.png"];
_hourHandView = [[UIImageView alloc] initWithImage:_hourHandImage];
_hourHandImage = [UIImage imageNamed:@"hour-hand.png"];
_hourHandView = [[UIImageView alloc] initWithImage:_hourHandImage];
[self.view addSubview:_hourHandView];

_hourHandView.layer.anchorPoint = CGPointMake(0.5f, 0.5f);
_hourTransform = CGAffineTransformMakeTranslation(centerX, centerY);
_hourTransform = CGAffineTransformTranslate(_hourTransform, -17, -127);
_hourTransform = CGAffineTransformRotate(_hourTransform, hours / 12.0 * M_PI * 2.0);
_minuteTransform = CGAffineTransformMakeTranslation(centerX, centerY);
_minuteTransform = CGAffineTransformTranslate(_minuteTransform, -10, -182);
_minuteTransform = CGAffineTransformRotate(_minuteTransform, minutes / 60.0 * M_PI * 2.0);
_hourHandView.transform = _hourTransform;
_minuteHandImage = [UIImage imageNamed:@"minute-hand.png"];
_minuteHandView = [[UIImageView alloc] initWithImage:_minuteHandImage];
_minuteHandView.transform = _minuteTransform;
[self.view addSubview:_minuteHandView];
_minuteTransform = CGAffineTransformRotate(_minuteTransform, minutes / 60.0 * M_PI * 2.0);
_secondHandImage = [UIImage imageNamed:@"second-hand.png"];
_secondTransform = CGAffineTransformMakeTranslation(centerX, centerY);
_secondTransform = CGAffineTransformTranslate(_secondTransform, -10, -189);
_secondTransform = CGAffineTransformRotate(_secondTransform, seconds / 60.0 * M_PI * 2.0);
_secondHandView = [[UIImageView alloc] initWithImage:_secondHandImage];
_secondHandView.transform = _secondTransform;
[self.view addSubview:_secondHandView];
}

--编辑--

我将一种方法重构为两种方法,一种用于初始显示,一种用于增量更新。增量更新方法似乎只调用了一次,因为时钟被冻结并且签名日志语句只调用了一次。

我现在有,对于更新部分:

- (void)render
{
    [self renderScreenInitial];
    [NSTimer scheduledTimerWithTimeInterval:0.002
                                     target:self
                                   selector:@selector(renderingTimer:)
                                   userInfo:nil
                                    repeats:YES];
}

- (void) renderScreenIncremental
{
    int height = floor([[UIScreen mainScreen] bounds].size.height + .4);
    int width = floor([[UIScreen mainScreen] bounds].size.width + .4);
    if (!UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation))
    {
        int juggle = height;
        height = width;
        width = juggle;
    }
    double decibelAngle = M_PI / 4 + (_decibel / 60) * M_PI / 2;
    double decibelAngleDifference = decibelAngle - _previousDecibelAngle;
    _previousDecibelAngle = decibelAngle;
    NSLog(@"%lf %lf", _decibel, decibelAngle);
    _decibelNeedleView = [[UIImageView alloc] initWithImage:_decibelNeedle];
    // CGAffineTransform decibelTransform = CGAffineTransformMakeTranslation(centerX, centerY);
    CGAffineTransform decibelTransform = CGAffineTransformMakeRotation(decibelAngleDifference);
    decibelTransform = CGAffineTransformTranslate(decibelTransform, sin(decibelAngle - .06) * -298, -cos(decibelAngle - .06) * 298);
    _decibelNeedleView.transform = decibelTransform;
    [self.view addSubview:_decibelNeedleView];
    double timestampSeconds = [[NSDate date] timeIntervalSince1970];
    double timestampSecondsDifference = timestampSeconds - _previousTimestampSeconds;
    _previousTimestampSeconds = timestampSeconds;
    double hoursDifference   = fmod(timestampSecondsDifference / 86400, 24);
    double minutesDifference = fmod(timestampSecondsDifference /  3600, 60);
    double secondsDifference = fmod(timestampSecondsDifference,     60);
    NSLog(@"Milliseconds: %lf, Hours: %.0f, minutes: %.0f, seconds: %.0f", timestampSecondsDifference * 1000.0, hoursDifference, minutesDifference, secondsDifference);
    _hourHandView.transform = CGAffineTransformMakeRotation(hoursDifference);
    _minuteHandView.transform = CGAffineTransformMakeRotation(minutesDifference);
    _secondHandView.transform = CGAffineTransformMakeRotation(secondsDifference);
}

-(void)renderingTimer:(NSTimer *)timer {
    [self renderScreenIncremental];
}

感谢您的帮助。你明白为什么它应该更新一次显示然后不继续保持更新了吗?

谢谢,

【问题讨论】:

  • 您能否确认renderingTimer: 是否被调用?我假设您从主队列中调用了render?顺便说一句,每0.002 秒调用一次可能没有意义。我会将该计时器减少到某个合理的水平(例如每秒 30-60 次)。

标签: ios objective-c memory-management memory-leaks automatic-ref-counting


【解决方案1】:

首先,您应该使用 Instruments 中的分配工具来识别正在分配和未释放的内容。我建议你想要 WWDC 2012 视频iOS App Performance: Memory,它演示了这一点,除其他外。

使用 Instrument 的 Allocations 工具,您不会猜测正在分配和未释放的内容,而是可以使用 heapshots/generations 来识别在您选择的某个时间范围内正在分配和未释放的实际对象.您甚至可以深入查看最初分配有问题的对象的位置。

除此之外,看看您的代码,您似乎正在删除并重新添加容器,但没有任何东西进入容器。而且您正在添加时针/分针/秒针,但从不删除它们。也许您打算将它们添加到容器中?

另外,您的代码没有描述 _changed 所做的事情,但如果那是 YES,那么您实际上是在创建一个 _containerView,将其从其父视图中删除(即使它从未添加到父视图中) ),然后丢弃它并创建另一个_containerView。很奇怪。

我还从这段代码推断出您将多次调用renderScreen。如果这是真的,那么我可能建议将视图内容的“创建”(添加背景、各种图像等)与视图的“更改”(transform 值的调整)分开。如果可能,您应该添加一次视图,然后在更新时执行最低限度的操作(更改转换)。

【讨论】:

  • 谢谢;我确实想观看 iOS App Performance: Memory。不幸的是,Safari 在停止播放之前只播放前三分钟的预告片,而且我还没有让它在 iTunes 中加载。 )-: _containerView 是早期效果的残留物。但是,我认为可行的主要是将原始设置与增量重复调整分开。到那个...
  • 如果你有一个付费的 iOS 开发者账户,所有的 WWDC 视频都可以在available免费观看。 iOS 开发者帐户的费用为 99 美元。
【解决方案2】:

使用您正在使用的 API 逐渐增加内存是预期行为。 [UIImage imageNamed:]will cache the image。如果您想测试这些是否在刷新缓存时被释放,请导致发生内存警告。您可以在模拟器中通过转到Hardware 菜单并选择Simulate Memory Warning 来执行此操作。

您也可以使用以下代码在设备上以编程方式执行此操作:

[[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidReceiveMemoryWarningNotification 
                                                    object:[UIApplication sharedApplication]];

您不应使用此代码发布生产应用程序

【讨论】:

  • 1.是的,使用imageNamed 缓存会导致内存增长,因为您的应用程序使用越来越多的不同图像。但是如果应用程序重复访问相同的图像,内存使用量就不会像这样爬升。所以这是一个很好的观察结果,困扰着许多对很少使用的图像使用 imageNamed 的应用程序草率,但我认为这不是问题所在。
猜你喜欢
  • 2012-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 2010-12-23
  • 1970-01-01
相关资源
最近更新 更多