2011-05-28 98 views
0

到目前爲止我的代碼分配INT新INT

- (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 的anount這工作正是我想它,但我想theBlockxCord設置爲每一個新的變量時間。所以最終的結果會是這樣的:

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

而不是每次都覆蓋BlockXCord。

獎勵積分,有沒有一種方法來在陣列也許打電話給他們,所以我沒有繼續這樣做:

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

回答

2

您可以使用C數組或一個NSMutableArray。您必須先將int s轉換爲NSNumber,然後才能將其添加到陣列中。

- (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. 
} 
+0

感謝您的獎金,但原來的問題仍然在減少。 – evdude100 2011-05-28 04:58:39

+0

我沒有得到你。用這個替換當前的任務,它應該工作,對吧? – 2011-05-28 05:00:20

+0

也許我很困惑[blockXCoord addObject:[NSNumber numberWithInt:(arc4random()%4)];它添加到的陣列在哪裏? – evdude100 2011-05-28 05:01:34

2

對於你的第一個問題:把你的結果放在一個常規的數組中,就像任何C程序或者NSMutableArray一樣。對於第二個問題:如果您使用NSMutableArray來存儲對象(比如NSNumber),您可以調用containsObject:來確定對象是否在數組中。 http://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/instm/NSArray/containsObject

+0

containsObject聽起來不錯!謝謝 :-) – evdude100 2011-05-28 05:07:17