问题描述
|
到目前为止,我有代码
- (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的起点
这完全符合我的期望,但是我想每次将theBlockxCord设置为一个新变量。因此,最终结果将类似于:
theBlockxCordOfBlock1=2
theBlockxCordOfBlock2=4
theBlockxCordOfBlock3=1
theBlockxCordOfBlock4=3
而不是每次都覆盖BlockXCord。
对于奖励积分,是否可以通过数组调用它们,所以我不必继续这样做:
if (theBlockxCordOfBlock1 == 2 || theBlockxCordOfBlock3 == 2 ..etc)
{
do stuff..
}
解决方法
您可以使用C数组或NSMutableArray。您必须先将3转换为4才能将其添加到数组中。
- (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.
}
, 对于第一个问题:将结果放入与任何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: