drawRect崩溃 - EXEC BAD ACCESS

时间:2011-06-19 03:03:26

标签: iphone cocoa-touch drawrect

我的应用在自定义UIView drawRect中崩溃。 崩溃只发生在内存不足的情况下。 (在我运行一些游戏或应用程序后,将我的应用程序从后台转到前台) 在崩溃之前,它触发了几次drawRect,其中一个,崩溃......

- (void)drawRect:(CGRect)rect {
        NSLog(@"  ## it is in drawRect");
    //NSLog(@"timecardImage: %@ ",[timecardImage description]);
    [timecardImage drawAtPoint:(CGPointMake(0.0f, 0.0f))];
}

崩溃TB:

#0  0x31db6c9a in objc_msgSend ()
#1  0x000051c8 in -[Timecard drawRect:] (self=<value temporarily unavailable, due to optimizations>, _cmd=<value temporarily unavailable, due to optimizations>, rect={origin = {x = 0, y = 0}, size = {width = 75, height = 108}}) at /xcode_prj/TimesheetKeeper/Classes/Timecard.m:72
#2  0x34caba04 in -[UIView(CALayerDelegate) drawLayer:inContext:] ()
#3  0x37221fac in -[CALayer drawInContext:] ()
#4  0x37221d2a in backing_callback ()
#5  0x3722177c in CABackingStoreUpdate ()
#6  0x3722117e in -[CALayer _display] ()
#7  0x37220e8c in -[CALayer display] ()
#8  0x3721570c in CALayerDisplayIfNeeded ()
#9  0x372151cc in CA::Context::commit_transaction ()
#10 0x37214fd6 in CA::Transaction::commit ()
#11 0x37213906 in CA::Transaction::pop ()
#12 0x37213884 in +[CATransaction commit] ()
#13 0x34df7bd2 in _UIWindowUpdateVisibleContextOrder ()
#14 0x34df7c66 in +[UIWindow _prepareWindowsForAppResume] ()
#15 0x34df03e4 in -[UIApplication _handleApplicationResumeEvent:] ()
...

以下是我如何设置UIView - self.timecard:

-(void)setupTimecard{
    if (!self.timecard) {       
    self.timecard = [[Timecard alloc] init];
    [self.timecard retain];
    }

    timecard.center = CGPointMake(self.view.center.x,10.0f);
    [self.view insertSubview:timecard atIndex:2];
    }

并且,我评论了viewController的didReceiveMemoryWarning。 在viewDidUnload中,我甚至对“timecard”什么都不做 只需在Dealloc中发布它。

这个问题花了我好几天,我仍然不知道。 你们提供的任何想法,我都会尝试。 谢谢你的帮助。


##完成了! ##

-(id)init {

UIImage *image = [UIImage imageNamed:@"timecard3.png"] ;
timecardImage = image;
    [timecardImage retain];    // #1 this is the key.

CGRect frame = CGRectMake(0, 0, image.size.width, image.size.height);
    self = [self initWithFrame:frame];
return self;
}

在drawRect中,timecardImage是drawAtPoint的接收者,它只是一个指向自动释放图像的指针。 在内存警告问题中,释放了自动释放图像。我的timecardImage也是如此。 添加#1行后,只需保留, EXC BAD ACCESS永远不会发生。

谢谢你们。

1 个答案:

答案 0 :(得分:0)

timeCardImage很可能被解除分配。如果您retain(您应该这样做),则应release nil timeCardImage跟随release。这假设您在低内存情况下{{1}}值。