Cocos2D项目中的神秘内存泄漏

时间:2012-12-12 16:59:49

标签: objective-c memory-management memory-leaks cocos2d-iphone

当我调用以下代码时,我正在泄漏内存。我已经尝试过显而易见的事情(在我完成它之后释放对象,并返回一个自动释放的对象)但是我收到以下错误:

  

[CCTouchJoint release]:发送到解除分配的实例0x1dd10f30的消息

在主循环中:

CCTouchJoint *tj = [CCTouchJoint touch:touch withMouseJoint:mouseJoint];
[touchJointList addObject:tj];

[touchJointsHaveNotMoved addObject:tj];
//*If I add [tj release] here we crash

在CCTouchJoint.h

@interface CCTouchJoint : NSObject
{
@public
    b2MouseJoint *mouseJoint;
    UITouch *touch;
}
@property (assign) b2MouseJoint *mouseJoint;
@property (nonatomic, retain) UITouch *touch;

在CCTouchJoint.mm

- (void)dealloc
{
    [touch release];
    [super dealloc];
}

- (id)initLocal:(UITouch *)_touch withMouseJoint:(b2MouseJoint *)_mouseJoint
{
    if ((self = [super init]))
    {
        self.touch = _touch;
        mouseJoint = _mouseJoint;
    }
    return self;
}

+ (id)touch:(UITouch *)_touch withMouseJoint:(b2MouseJoint *)_mouseJoint
{
    return [[self alloc] initLocal:_touch withMouseJoint:_mouseJoint];
   //*If I return an autoreleased object here we crash
}

- (void)destroyTouchJoint
{
    if (mouseJoint != NULL)
    {
        mouseJoint->GetBodyA()->GetWorld()->DestroyJoint(mouseJoint);
    }
}

在级别退出或重新启动

-(void)removeAllTouchjoints:(BOOL)release{
    //remove touchjoints
    for (CCTouchJoint *tj in touchJointList)
    {
        [tj destroyTouchJoint];
    }

    for (CCTouchJoint *tj in touchJointsHaveNotMoved)
    {
        [tj destroyTouchJoint];
    }

    [touchJointList             removeAllObjects];
    [touchJointsHaveNotMoved    removeAllObjects];

}

1 个答案:

答案 0 :(得分:0)

在你的init方法中你使用setter(self.touch = ...),你不应该这样做。 分配给iVar并直接保留。

当您返回自动释放的对象或向其他方法添加版本时崩溃(异常消息)是什么?

修改

好的,我无法使用您提供的代码重现您的错误。所以它必须在班级的其他地方。什么是错误消息?

编辑2

如果,而不是

,该怎么办?
CCTouchJoint *tj = [CCTouchJoint touch:touch withMouseJoint:mouseJoint];
[touchJointList addObject:tj];

[touchJointsHaveNotMoved addObject:tj];
//*If I add [tj release] here we crash
你做了

CCTouchJoint *tj = [CCTouchJoint alloc] initLocal: touch withMouseJoint:mouseJoint];
[touchJointList addObject:tj];

[touchJointsHaveNotMoved addObject:tj];
[tj release]; //does it crash here?? What message?