I've been struggling with a problem that I hope someone can help me with.
I have Class called 'GameObjectDefinitionTable', where I set all my object properties, which is in another class called 'Product'. In my 'HelloWorldScene' I allocate 'GameObjectDefinitionTable' which in turn creates several 'Product's. Like this:
HelloWorldScene -> GameObjectDefinitionTable -> Product
I then want to return a 'Product' to 'HelloWorldScene. But here is where I get problems. Some code:
HelloWorldScene:
GameObjectDefinitionTable *god = [[GameObjectDefinitionTable alloc]init];
Product* currentProduct = [god getProductWithNum:0];
NSLog(@"currenProduct (name): %@",currentProduct.name); //Crash
GameObjectDefinitionTable:
-(void) createProducts {
Product *product;
for (int i=0; i<[allProductsWithDefinitions count];i++ ) {
product = [[Product alloc]init];
开发者_如何学Python product.name = [[allProductsWithDefinitions objectAtIndex:i] objectAtIndex:0];
product.density = [[[allProductsWithDefinitions objectAtIndex:i] objectAtIndex:1] floatValue];
product.scoreValue = [[[allProductsWithDefinitions objectAtIndex:i] objectAtIndex:2] intValue];
product.fileName = [[allProductsWithDefinitions objectAtIndex:i] objectAtIndex:3];
[products addObject:product];
[product release];
}
[allProductsWithDefinitions release];
}
-(Product *) getProductWithNum:(int)tNum {
Product *tempProduct;
tempProduct = [products objectAtIndex:tNum];
return tempProduct;
[tempProduct release];
}
The arrays and all in 'GameObjectDefinitionTable' is working fine if I log in that class.
Would be really grateful for an answer :)
Is it the case you need something like:
- (Product *)getProductWithNum:(int)tNum
{
Product *tempProduct = [[products objectAtIndex:tNum] retain];
return [tempProduct autorelease];
}
Product *tempProduct;
tempProduct = [products objectAtIndex:tNum];
return tempProduct;
[tempProduct release];
Is that what you mean to have? You kind of have two big problems cancelling each other out here. The [tempProduct release];
line is unreachable. The second, if you were to actually execute [tempProduct release];
before the return, you would be releasing the memory, and then accessing the currentProduct.name
property of what is essentially a dangling pointer. This illegal memory access could cause your Bad Exec.
Since you are not allocating, copying, or retaining tempProduct
, you must NOT release it. Why not just a simple return [products objectAtIndex:tNum];
?
精彩评论