【问题标题】:Creating an integer array in sprite kit Xcode在精灵套件 Xcode 中创建一个整数数组
【发布时间】:2015-10-14 12:35:21
【问题描述】:

关于这个话题我真的没什么可说的,因为我找不到任何关于它的东西。我只想要一个整数数组,我可以在我的 iOS 游戏中参考这些整数的价格。例如

Array priceArray = Array(50);

itemAPrice = Array (0);
itemBPrice = Array (1);

我知道它效率不高,但纯粹是一个例子。 任何关于在 sprite kit 中创建整数/NSInteger 数组的主题都会有所帮助。

提前致谢 -瑞安

【问题讨论】:

  • 你的阵列的条件是什么? xy 之间的 50 个随机价格?你使用什么语言,ObjC 还是 Swift?
  • @ZoffDino 我在目标 c 中对此进行编码,我想分配数组的价格。我想手动将数据输入到数组中,如果有意义的话,让某些对象稍后检索它们:)

标签: ios objective-c arrays xcode int


【解决方案1】:

NSArray 在 Objective-C 中是不可变的。你应该使用NSMutableArray,它是NSArray的子类:

// Create the array. Capacity is only a suggestion, not a hard limit
NSMutableArray * priceArray = [NSMutableArray arrayWithCapacity:50];

// You can't add doubles directly to the array. Wrap it inside NSNumber
[priceArray addObject:@0.0];
[priceArray addObject:@1.0];
// ...
[priceArray addObject:@49.0];

// Now get it back
double itemAPrice = [priceArray[0] doubleValue];
double itemBPrice = [priceArray[1] doubleValue];

【讨论】:

    【解决方案2】:

    你遇到过 NSMutableArray 吗?您可以使用它来初始化数组

    NSMutableArray *array = [NSMutableArray createWithObjects: /*comma separated list of int's*/];
    

    使用removeLastElementaddElements 方法可以更快地添加和删除元素,因为它们不必重新排列数组。但如果需要,您可以使用 insertObject: /*object*/ atIndex: /*int*/removeObjectAtIndex: /*int*/

    对于 NSMutableArray,我相信与 NSArray 一样,您可以使用方括号表示法来引用元素,即 array[i] = /int i 处的元素/。

    【讨论】:

      【解决方案3】:

      你可以像这样用 NSNumbers 做到这一点:

      typedef NS_ENUM(NSInteger, ItemPrice) {
        ItemOne = 0,
        ItemTwo,
        ItemThree,
        ItemFour
      };
      
      // Make it mutable so we can add more prices later if we want.
      NSMutableArray *itemPrices = [@[@12, @33, @26, @44] mutableCopy];
      NSNumber *itemPrice = [itemPrices objectAtIndex:ItemThree];
      NSLog(@"Item Price: %@", itemPrice);
      

      将导致:

      Item Price: 2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-27
        • 2021-03-07
        • 2019-04-12
        • 1970-01-01
        相关资源
        最近更新 更多