gpt4 book ai didi

ios - 内存泄漏,但 CGContextRelease 破坏了 View

转载 作者:行者123 更新时间:2023-11-28 23:47:09 24 4
gpt4 key购买 nike

我遇到了内存问题:

使用自定义 Background.m 类,我根据传递给类的颜色选择创建渐变背景。出现的问题是似乎有泄漏,没有什么令人兴奋的,但随着时间的推移会累积起来。释放 drawRect 中的上下文消除了内存问题,但是没有绘制渐变。最好的解决方案/解决方法是什么?使用苹果的渐变?下面是传递给 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);

最佳答案

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

首先,您没有为 CFArrayCreateMutable 平衡 Release

其次,您正在发布不属于您的东西 (ref)。

相关的,每个 malloc 都必须由一个 free 来平衡,所以你在泄漏 locations

你的清理代码应该是

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

关于ios - 内存泄漏,但 CGContextRelease 破坏了 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52508020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com