感谢 hotpaw2 解决了我的增量绘图问题。唉,我在实现该解决方案时发现了一个问题。当我按下 iPhone 底部的按钮暂停应用程序然后重新启动它时,它显示为内存引起的崩溃。 (只要我不这样做,我就可以无限期地运行该应用程序)。崩溃发生在下面指示的行处,该行发生在 UIView 的子类 FooBar 中:
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
// @@CRASH here: Program received signal EXC_BAD_ACCESS
[backingLayer renderInContext:ctx]; // Render the backing layer into current context
[self randomRectangle: ctx];
}
在 FooBar 的界面中,我已将支持层声明为实例变量:
@private
NSTimer* timer;
CALayer *backingLayer;
在 FooBar 的实现中,backingLayer 在 initWithFrame
中再次出现一次,如下段落:
backingLayer = self.layer;
// [backingLayer retain];
// Set its color space and background color
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat components[4] = {0.0f, 0.0f, 0.0f, 1.0f};
CGColorRef bgColor = CGColorCreate(colorSpace, components);
backingLayer.backgroundColor = bgColor;
CGColorRelease(bgColor);
CGColorSpaceRelease(colorSpace);
我还应该说,initWithFrame
中定义的 NSTimer 计时器
每秒触发 tick
方法低于 12 次:
- (void)tick
{
// Tell the view that it needs to re-draw itself
if (running) { // Go!
// NSLog(@"frameRate: %2.1f, frameCount: %d", frameRate, frameCount);
[self setNeedsDisplay];
frameCount++;
}
}
我已在此应用程序上运行 Instruments。未检测到内存泄漏。但是,当我运行分配并 (a) 使用物理按钮暂停应用程序,(b) 触摸应用程序图标以使其再次运行时,然后我看到巨大的分配集群(~2 GB)——然后崩溃。
--吉姆
最佳答案
请参阅最后一条评论,我应该将其放在这里。通过在应用进入非事件状态时将 BOOL running
设置为 FALSE 并在应用再次变为事件状态时将其重置为 TRUE 来修复此问题。
关于iphone - CALayer 崩溃、内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4791173/