开发者

NSArray Problem

开发者 https://www.devze.com 2023-01-11 00:15 出处:网络
i try to generate开发者_运维技巧 6 random numbers and put them in a global NSArray, thats what i have done:

i try to generate开发者_运维技巧 6 random numbers and put them in a global NSArray, thats what i have done:

in MainViewController.h

NSArray * zufallsZahlen;

i have function to generate the Numbers:

- (NSArray *)generateNumbers {
  NSMutableSet *s = [NSMutableSet set];
  while([s count] < 6) {
    NSNumber *z = [NSNumber numberWithUnsignedInteger:arc4random() % 46];
    if(![s containsObject:z]) 
    [s addObject:z];
  }
NSArray *zahlen = [[s allObjects] sortedArrayUsingSelector:@selector(compare:)];

return zahlen;
}

Now in the ViewDidLoad:

zufallsZahlen = [self generateNumbers];
[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];

If i NSLog my zufallsZahlen NSArray in the ViewDidLoad i get the Output i want:

(
2,
8,
13,
16,
27,
31
)

The onTimer function creates every 0.2 seconds a ball with the actual Number:

-(void)onTimer:(NSTimer*)timer {
if (indexBall > 6){
    //some function
}
else {
    [self crateBall:[zufallsZahlen objectAtIndex:indexBall] ballId:indexBall ballX:xCoord ballY:100];
    [self rollBall:indexBall rollToY: 80];
    indexBall+=1;
    xCoord-=40;

    NSLog(@"%@", zufallsZahlen);
}

And if i Nslog the Array in the onTimer function i get the fooling Output:

Japanese.lproj

EDIT:

in viewDidLoad simply retain the NSArray:

zufallsZahlen = [self generateNumbers];
[zufallsZahlen retain];


You didn't retain the array. Remember that methods like [NSSet sortedArrayUsingSelector:] return an array that is autoreleased.

Hope that helps.


You can pass zufallsZahlen in the timer:

zufallsZahlen = [self generateNumbers];
[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(onTimer:) userInfo:zufallsZahlen repeats:YES];

- (void) onTimer:NSArray *zufallsZahlen {
    // Do something with zufallsZahlen
}
0

精彩评论

暂无评论...
验证码 换一张
取 消