【问题标题】:returning an NSObject - bad exec返回一个 NSObject - 错误的执行
【发布时间】:2011-02-02 12:33:54
【问题描述】:

我一直在努力解决一个问题,希望有人可以帮助我。

我有一个名为“GameObjectDefinitionTable”的类,我在其中设置了我的所有对象属性,它位于另一个名为“Product”的类中。在我的“HelloWorldScene”中,我分配了“GameObjectDefinitionTable”,它又创建了几个“Product”。像这样:

HelloWorldScene -> GameObjectDefinitionTable -> 产品

然后我想将一个“产品”返回给“HelloWorldScene”。但这是我遇到问题的地方。一些代码:

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];
        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]; 
}

如果我登录该类,则“GameObjectDefinitionTable”中的数组和所有内容都可以正常工作。

非常感谢您的回答:)

【问题讨论】:

    标签: xcode ios return nsobject


    【解决方案1】:

    是不是你需要这样的东西:

    - (Product *)getProductWithNum:(int)tNum
    {
      Product *tempProduct = [[products objectAtIndex:tNum] retain];
      return [tempProduct autorelease];
    }
    

    【讨论】:

      【解决方案2】:

      Product *tempProduct;

      tempProduct = [products objectAtIndex:tNum];

      return tempProduct;

      [tempProduct release];

      这就是你的意思吗?你有两个大问题在这里相互抵消。 [tempProduct release]; 行无法访问。第二,如果您在返回之前实际执行[tempProduct release];,您将释放内存,然后访问本质上是一个悬空指针的currentProduct.name 属性。这种非法的内存访问可能会导致您的 Bad Exec。

      由于您不分配、复制或保留tempProduct,因此您不得释放它。为什么不只是一个简单的return [products objectAtIndex:tNum];

      【讨论】:

      • 谢谢你的回答,我认为彼得为我解决了这个问题:)
      猜你喜欢
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 2021-09-21
      • 2020-11-17
      • 2020-02-04
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      相关资源
      最近更新 更多