0

I am running this code, because I want to change something on all the buttons within my ViewController when it starts.

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    int i = 1;
    
    for (UIButton *btn in self.view.subviews)
    {
        NSLog(@"Count I - %d ", i);
        //NSLog(@"Count I - %d - %@", i, btn.titleLabel.text);
        
        i++;
    }
}

The Output it:

2013-11-11 08:15:13.315 testingSingle[7876:a0b] Count I - 1

2013-11-11 08:15:13.317 testingSingle[7876:a0b] Count I - 2

Now this seems strange to me, because it is a new project and nothing has been dragged onto or even changed on the VC in the storyboard or in code - there is nothing to suggest that there 2 UIButtons.

How can I get this message to return 0 if this is the case? My app crashes because of this.

Community
  • 1
  • 1
jwknz
  • 6,598
  • 16
  • 72
  • 115

1 Answers1

2

Changing your NSLog to

NSLog(@"%@", [btn class]);

gives the output

_UILayoutGuide 
_UILayoutGuide

which shows that there are no buttons, but some other views (perhaps required for Autolayout).

for (UIButton *btn in self.view.subviews)

enumerates all subviews, it does not matter that the loop variable btw is declared as UIButton *. To handle only buttons, you have to test the class of each object:

for (UIView *subView in self.view.subviews) {
    if ([subView isKindOfClass:[UIButton class]]) {
        UIButton *btn = (UIButton *)subView;
        // Do something with btn ...
        i++;
    }
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 1
    If one wished to have an array of buttons in general, `-[NSArray filteredArrayUsingPredicate:]` and an [`NSPredicate` testing class membership](http://stackoverflow.com/questions/2554894/is-it-possible-to-filter-an-nsarray-by-class/19894246) could also be used. – Carl Veazey Nov 10 '13 at 19:45