Object type changes
I'm having a bit of an issue with holding a mixture of a custom class and UIImage views in an array. These are stored in the array and I'm using:
if ([[fixtures objectAtIndex:index] isKindOfClass:[Fixture class]])
to distinguish between if it's a UIIMage or Fixture object. My source code for this is:
- (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];
}
}
However, when dragging the cell that was an object of class Fixture, I would get errors such as EXC_BAD_ACCESS or unrecognized selector sent to instance (which makes sense as it was sending a CALayerArray a scale command.
I therefore set a breakpoint to see inside the fixtures array. Here I saw that the UIImages were all set to the right class type but there was also:
- (CALayerArray *)
- (Fixture *)
- (NSObject *)
for the positions were the Fixture classes were being held in the array. Could anyone shed some light onto why it's doing this? If you need any more info to help please feel free to ask.
Denis
In your code here:
Fixture *newFixture = [[Fixture alloc] init];
newFixture = [fixtures objectAtIndex:index];
dragCell.icon = [UIImage imageNamed:newFixture.fixtureStringPath];
[newFixture release];
It looks like you're releasing an autorelease object (newFixture
). When you get an object out of the array, it's autorelease.
You also have a memory leak, when you allocate the newFixture at the first line, that object is never released because you replace the pointer to it in your 2nd line.
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
So the code should be like
Fixture *newFixture = [fixtures objectAtIndex:index];
dragCell.icon = [UIImage imageNamed:newFixture.fixtureStringPath];
Then your property should retain the image correctly.
精彩评论