【问题标题】:Assign int to new int将 int 分配给新的 int
【发布时间】:2011-09-03 19:41:08
【问题描述】:

到目前为止我有代码

- (void)CreatenewBlock:(int)blockCountToSpawn
{
    for (int i=0; i != blockCountToSpawn; i++) 
    {
        theBlockxCord = arc4random() % 4;
        theBlockyCord = arc4random() % 4;
        NSLog(@"New Block with Cords (%i, %i)",theBlockxCord, theBlockyCord);
    }

}

这个循环直到它到达blockCountToSpawn的anunt 这完全符合我的要求,但我想每次都将 theBlockxCord 设置为一个新变量。所以最终结果会是这样的:

theBlockxCordOfBlock1=2
theBlockxCordOfBlock2=4
theBlockxCordOfBlock3=1
theBlockxCordOfBlock4=3

而不是每次都覆盖 BlockXCord。

对于奖励积分,是否有一种方法可以在数组中调用它们,所以我不必继续这样做:

if (theBlockxCordOfBlock1 == 2 || theBlockxCordOfBlock3 == 2 ..etc)
{
   do stuff..
}

【问题讨论】:

    标签: objective-c variables int


    【解决方案1】:

    您可以使用 C 数组或 NSMutableArray。您必须先将 ints 转换为 NSNumbers,然后才能将其添加到数组中。

    - (void)CreatenewBlock:(int)blockCountToSpawn
    {
        NSMutableArray *blockXCoord = [NSMutableArray array]; // Retain it as needed.
        NSMutableArray *blockYCoord = [NSMutableArray array];
        for (int i=0; i != blockCountToSpawn; i++) 
        {
            [blockXCoord addObject:[NSNumber numberWithInt:(arc4random() % 4)];
            [blockYCoord addObject:[NSNumber numberWithInt:(arc4random() % 4)];
        }
    
        ...
    }
    

    如果您想搜索2,请执行此操作

    if ( [blockXCoord indexOfObject:[NSNumber numberWithInt:2]] != NSNotFound ) {
        ... do stuff
    }
    

    if ( [blockXCoord containsObject:[NSNumber numberWithInt:2]] ) {
        ... do stuff
    }
    

    编辑

    for ( int i = 0; i < [blockXCoord count]; i++ ) {
        NSPoint point = NSMakePoint([[blockXCoord objectAtIndex:i] intValue],[[blockYCoord objectAtIndex:i] intValue]);
    
        ... do something with the point.
    }
    

    【讨论】:

    • 感谢奖金,但最初的问题仍在减少。
    • 我没听懂你。用这个替换当前的分配,它应该可以工作,对吧?
    • 也许我对 [blockXCoord addObject:[NSNumber numberWithInt:(arc4random() % 4)]; 感到困惑它要添加到的数组在哪里?
    • indexOfObject: 肯定会工作,但我认为 containsObject: 更容易理解和维护。
    • @Deepak 谢谢!如果我想将数组中的所有内容与单个 int 进行比较,例如: if ([blockXCoord indexOfObject:[NSNumber numberWithInt:all]] != playerxcord)
    【解决方案2】:

    对于您的第一个问题:将您的结果放入像任何 C 程序一样的传统数组或 NSMutableArray。 http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html

    对于第二个问题:如果您使用 NSMutableArray 来存储对象(例如 NSNumber),则可以调用 containsObject: 来确定对象是否在数组中。 http://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/instm/NSArray/containsObject:

    【讨论】:

    • containsObject 听起来很棒!谢谢:-)
    猜你喜欢
    • 2013-10-15
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 2019-05-18
    • 2023-04-08
    • 2018-02-03
    • 2016-07-04
    相关资源
    最近更新 更多