对象类型更改

时间:2011-04-20 17:17:47

标签: iphone objective-c ios ios4 exc-bad-access

我在一个数组中混合使用自定义类和UIImage视图时遇到了一些问题。这些存储在数组中,我正在使用:

 if ([[fixtures objectAtIndex:index] isKindOfClass:[Fixture class]]) 

区分它是UIIMage还是Fixture对象。我的源代码是:

    - (void) moveActionGestureRecognizerStateChanged: (UIGestureRecognizer *) recognizer
    {
     switch ( recognizer.state )
        {
       case UIGestureRecognizerStateBegan:
            {
                NSUInteger index = [fixtureGrid indexForItemAtPoint: [recognizer locationInView: fixtureGrid]];
                emptyCellIndex = index;    // we'll put an empty cell here now

                // find the cell at the current point and copy it into our main view, applying some transforms
                AQGridViewCell * sourceCell = [fixtureGrid cellForItemAtIndex: index];
                CGRect frame = [self.view convertRect: sourceCell.frame fromView: fixtureGrid];
                dragCell = [[FixtureCell alloc] initWithFrame: frame reuseIdentifier: @""];

                if ([[fixtures objectAtIndex:index] isKindOfClass:[Fixture class]]) {
                    Fixture *newFixture = [[Fixture alloc] init];
                    newFixture = [fixtures objectAtIndex:index];
                    dragCell.icon = [UIImage imageNamed:newFixture.fixtureStringPath];
                    [newFixture release];  
                } else {
                    dragCell.icon = [fixtures objectAtIndex: index];
                }
                [self.view addSubview: dragCell];
    }
}

但是,当拖动作为类Fixture的对象的单元格时,我会收到错误,例如EXC_BAD_ACCESS或无法识别的选择器发送到实例(这是有意义的,因为它发送了CALayerArray缩放命令。

因此我设置了一个断点来查看fixtures数组。在这里,我看到UIImages都被设置为正确的类类型,但也有:

  • (CALayerArray *)
  • (夹具*)
  • (NSObject *)

的位置是Fixture类被保存在数组中。谁能解释为什么会这样做?如果您需要更多信息帮助,请随时询问。

丹尼斯

1 个答案:

答案 0 :(得分:4)

在您的代码中:

Fixture *newFixture = [[Fixture alloc] init];
newFixture = [fixtures objectAtIndex:index];
dragCell.icon = [UIImage imageNamed:newFixture.fixtureStringPath];
[newFixture release];

看起来你正在发布一个自动释放对象(newFixture)。当你从数组中获取一个对象时,它就是自动释放。 您也有内存泄漏,当您在第一行分配newFixture时,该对象永远不会被释放,因为您在第二行中替换了它的指针。

Fixture *newFixture = [[Fixture alloc] init];  // THIS OBJECT IS NEVER RELEASED
newFixture = [fixtures objectAtIndex:index]; // YOU'RE REPLACING THE newFixture POINTER WITH AN OBJECT FROM THE ARRAY
dragCell.icon = [UIImage imageNamed:newFixture.fixtureStringPath];
[newFixture release]; // YOU'RE RELEASING AN AUTORELEASED OBJECT

所以代码应该像

Fixture *newFixture = [fixtures objectAtIndex:index];
dragCell.icon = [UIImage imageNamed:newFixture.fixtureStringPath];

然后你的财产应该正确保留图像。