【问题标题】:Objective-C, sorting an array based on a objects instance variable.Objective-C,基于对象实例变量对数组进行排序。
【发布时间】:2009-11-05 23:09:34
【问题描述】:

我正在开发像《啮齿动物复仇》这样的游戏,只是为了指出我从哪里来提出这个问题。我也在用cocos2d游戏引擎...

我有一个包含大约 168 个块的层,这些块是 Sprite 的子类。每个块包含两个整数实例变量,一个用于 xGridLocation 和 yGridLocation。我有一个我调用的方法,它返回一个数组,其中包含与您控制的主角(鼠标)在同一 x 或 y 行上的所有块。只要块保持相同的顺序(从最小的 x/y 值到最大),这种方法就可以工作,但是当我开始将块推出其原始行并将它们混合一点(玩游戏时)我的逻辑不更长的工作,因为它基于数组中的块根据它们的 xGridLocation 或 yGridLocation 从最小到最大索引的事实。 xGridLocation 和 yGridLocation 不基于它们的位置,当第一次加载图层时,它们会被赋予预设的网格位置,并且随着块向任何方向移动,网格位置会根据它们移动的方向而改变。

我的问题是如何在数组返回之前根据实例变量 xGridLocation 或 yGridLocation 对数组进行排序。我正在考虑使用 sortUsingSelector:@selector(compareValues:) 方法,但不确定如何实现将进行排序的 compareValues 方法。

这是我用来获取块数组的方法。

//I have another one for x. The y parameter is the mouses y value.
-(NSMutableArray *)getBlocksForY:(int)y
{
 NSMutableArray *blocks = [[NSMutableArray alloc] init];

 int tagNum = 0;

        //tagNum starts at 0, and goes up to 168, the numer of children (blocks) on
        //this layer...

 for(tagNum; tagNum<=168; tagNum++)
 {
  BlueBlock *currentBlock = (BlueBlock *)[self getChildByTag:tagNum];
  int currentY = [currentBlock getBlockLocationY];

                //Checks to see if the current block has same y value as the mouse, if
                //so it adds it to the array.
  if(currentY == y)
  {
   [blocks addObject:currentBlock];
  }
 }

        //I want to sort before returning...
 return blocks;
}

如果您需要更多信息,请询问。

【问题讨论】:

标签: objective-c arrays sorting cocos2d-iphone nsmutablearray


【解决方案1】:

如 NSMutableArray 参考中所述:

比较器消息被发送到每个 接收器中的对象,并作为其 单个参数中的另一个对象 大批。比较方法应该 返回 NSOrderedAscending 如果 接收器小于参数, NSOrderedDescending 如果接收者是 大于论点,并且 NSOrderedSame 如果它们相等。

所以你的比较器应该是这样的,并且应该添加到BlueBlock类:

- (NSInteger) compareBlocks:(BlueBlock)block
{
     if ([self getBlockLocationX] < [block getBlockLocationX])
          return NSOrderedAscending;
     else if ([self getBlockLocationX] == [block getBlockLocationX])
     {
          if ([self getBlockLocationY] < [block getBlockLocationY])
              return NSOrderedAscending;
          else if ([self getBlockLocationY] == [block getBlockLocationY])
              return NSOrderedSame;
          else
              return NSOrderedDescending;
     }
     else
         return NSOrderedDescending;
 }

【讨论】:

  • 谢谢,只需要根据我的需要稍微调整一下,效果很好!
  • :D 很高兴有用!但别忘了勾选正确的答案..
猜你喜欢
  • 2014-04-01
  • 1970-01-01
  • 2016-07-07
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多