James Dunay
James Dunay

Reputation: 2724

Basic Objective-C array 'for' loop assistance

So heres my hangup, I create an array, pass buttons into it and use a for loop in an attempt to place each button on the view. I know they will be in the same position because they both go through the same CGRectMake. However i cannot seem to place anything on the screen with this code, although it doesn't return any errors it still has me stumped as to why.

Anyone got any suggestions? Thanks!

- (void)practiceMethod{

 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Practice Method has begun" message:@"Alert" delegate: self cancelButtonTitle:@"Close" otherButtonTitles: nil];
 //[alert show];
 [alert release];

 float i=0;

 CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];

 UIImage *buttonGraphic = [UIImage imageNamed:@"1.png"];

 UIButton *buttonOne = [[UIButton alloc] initWithFrame:applicationFrame];
 UIButton *buttonTwo = [[UIButton alloc] initWithFrame:applicationFrame];

 buttonArray = [[NSArray alloc] initWithObjects:buttonOne, buttonTwo,nil];

 for (i = 0; i > [buttonArray count]; i++) {

  UIButton *tempElement = [buttonArray objectAtIndex:i];

  tempElement.frame = CGRectMake(140, 230, 50, 50);

  [tempElement setBackgroundImage:buttonGraphic forState:UIControlStateNormal];

  [self addSubview:tempElement];
 }
}

Upvotes: 1

Views: 3552

Answers (2)

grahamparks
grahamparks

Reputation: 16296

Replace:

for (i = 0; i > [buttonArray count]; i++) {
   UIButton *tempElement = [buttonArray objectAtIndex:i];
   ...

}

With the array looping shortcut syntax:

for (UIButton *tempElement in buttonArray) {
    ...

}

It's also better to use buttonWithType: with UIButton:

UIButton *buttonOne = [UIButton buttonWithType: UIButtonTypeCustom];
buttonOne.frame = applicationFrame;

Upvotes: 3

Thomson Comer
Thomson Comer

Reputation: 3919

Change

for (i = 0; i > [buttonArray count]; i++) {

to

for (i = 0; i < [buttonArray count]; i++) {

and you'll be up and running.

PS. I suggest you use Objective-Cs for each iterator for these kinds of problem:

for( UIButton* button in buttonArray )
{ 
    // stuff with button
}

Upvotes: 8

Related Questions