tags:

views:

39

answers:

2

Hi, 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

Im sorry for my bad english, thanks for help and greetings from switzerland.

EDIT:

in viewDidLoad simply retain the NSArray:

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

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
}
Matt Williamson
+2  A: 

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

Hope that helps.

Firoze Lafeer
Thank you very much that works for me :D
Mario