【问题标题】:Memory leak, but CGContextRelease destroys view内存泄漏,但 CGContextRelease 破坏视图
【发布时间】:2019-03-01 15:48:30
【问题描述】:

我遇到了内存问题:

使用自定义 Background.m 类,我正在根据传递给该类的颜色选择创建渐变背景。问题出现在似乎有泄漏,没有什么令人兴奋的,但随着时间的推移而积累。在 drawRect 中释放上下文消除了内存问题,但是没有绘制渐变。最好的解决方案/解决方法是什么?使用 Apple 的渐变?下面是传递给 Background 类的 drawRect 方法的代码:

    //1. create vars
    float increment = 1.0f / (colours.count-1);
    CGFloat * locations = (CGFloat *)malloc((int)colours.count*sizeof(CGFloat));
    CFMutableArrayRef mref = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);

    //2. go through the colours, creating cgColors and locations
    for (int n = 0; n < colours.count; n++){
        CFArrayAppendValue(mref, (id)[colours[n] CGColor]);
        locations[n]=(n*increment);
    }

    //3. create gradient
    CGContextRef ref = UIGraphicsGetCurrentContext();
    CGColorSpaceRef spaceRef = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradientRef = CGGradientCreateWithColors(spaceRef, mref, locations);

    if (isHorizontal){
        CGContextDrawLinearGradient(ref, gradientRef, CGPointMake(0.0, 0.0), CGPointMake(self.frame.size.width, 0.0), kCGGradientDrawsAfterEndLocation);
    } else if (isDiagonal) {
        CGContextDrawLinearGradient(ref, gradientRef, CGPointMake(0.0, 0.0), CGPointMake(self.frame.size.width, self.frame.size.height), kCGGradientDrawsAfterEndLocation);
    } else {
        CGContextDrawLinearGradient(ref, gradientRef, CGPointMake(0.0, 0.0), CGPointMake(0.0, self.frame.size.height), kCGGradientDrawsAfterEndLocation);
    }

    CGContextRelease(ref); //ISSUE
    CGColorSpaceRelease(spaceRef);
    CGGradientRelease(gradientRef);

【问题讨论】:

  • 您不拥有 ref。你借了一个

标签: ios memory drawrect


【解决方案1】:

每个CreateCopyRetain 必须由Release 平衡。你在这里违反了两次。

首先,ReleaseCFArrayCreateMutable 之间没有平衡。

其次,你发布了一些不属于你的东西 (ref)。

相关,每个malloc 必须由free 平衡,所以你正在泄漏locations

你的清理代码应该是

free(locations);
CGRelease(mref);
CGColorSpaceRelease(spaceRef);
CGGradientRelease(gradientRef);

【讨论】:

  • @E.Coms 谢谢。固定。
猜你喜欢
  • 2011-10-02
  • 2021-03-03
  • 2016-03-25
  • 1970-01-01
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多