分段错误的来源在哪里:11?

时间:2012-05-05 17:17:56

标签: objective-c struct segmentation-fault objective-c++

请帮忙,这是我在这里遇到的3个故障之一,我根本找不到它们的位置:我知道它们与我的结构有关但我不知道如何找到它们......这是第一部分代码有错误:

-(BOOL)detectCollisionBetweenEntityAtIndex:(int)index1 andEntityAtIndex:(int)index2
{
  if ((([entityArray objectAtIndex:index1].entityX >= [entityArray objectAtIndex:index2].entityX) && ([entityArray objectAtIndex:index1].entityX <= ([entityArray objectAtIndex:index2].entityX + [entityArray objectAtIndex:index2].entityWidth)) && ([entityArray objectAtIndex:index1].entityY >= [entityArray objectAtIndex:index2].entityY) && ([entityArray objectAtIndex:index1].entityY <= ([entityArray objectAtIndex:index2].entityY + [entityArray objectAtIndex:index2].entityLength))) || (([entityArray objectAtIndex:index1].entityX + [entityArray objectAtIndex:index1].entityWidth >= [entityArray objectAtIndex:index2].entityX) && ([entityArray objectAtIndex:index1].entityX + [entityArray objectAtIndex:index1].entityWidth <= ([entityArray objectAtIndex:index2].entityX + [entityArray objectAtIndex:index2].entityWidth)) && ([entityArray objectAtIndex:index1].entityY + [entityArray objectAtIndex:index1].entityLength  >= [entityArray objectAtIndex:index2].entityY) && ([entityArray objectAtIndex:index1].entityY + [entityArray objectAtIndex:index1].entityLength <= ([entityArray objectAtIndex:index2].entityY+ [entityArray objectAtIndex:index2].entityLength))))
  {
    return TRUE;
  }
  else
  {
    return FALSE;
  }
}

entityArray是一个NSMutable数组,其中填充了一个struct i的实例:

struct Entity
{
  int entityX;
  int entityY;
  int entityLength;
  int entityWidth;
  int entityType;
  int entitySpeed;
  bool isDead;
};

2 个答案:

答案 0 :(得分:3)

NSMutableArray只能存储Objective-C对象,而不能存储C结构。将实体包装在NSValue对象中以将它们存储在数组中:

Entity entity;
// populate entity...

NSValue *value = [NSValue valueWithBytes:&entity objCType:@encode(struct Entity)];
[array addObject:value];

要获取值,请使用-[NSValue getValue:],如下所示:

NSValue *value = [array objectAtIndex:index];
Entity entity;
[value getValue:&entity];

答案 1 :(得分:1)

有些事情:

    -(BOOL)detectCollisionBetweenEntityAtIndex:(int)index1 andEntityAtIndex:(int)index2
    {
    bool hasDetected = false;
      if (...)
      {
        hasDetected = TRUE;
      }
        else
      {
        hasDetected = FALSE;
      }
        return hasDetected ;
      }

应该解决它!