Search code examples
objective-ciosxcodensarrayiboutletcollection

Using IBOutletCollections


I have 30 UILabels I wish to use as IBOutlets. However when I try to access their UILabel properties I'm getting errors telling me that property x is not found for object of type 'id'. I'm very rusty with Objective C so suspect I've done something fundamentally wrong. I've assigned all my labels to the IBCollection within the xib file.

.h

@interface ViewController : UIViewController
{
    IBOutletCollection(UILabel) NSArray *statPanels;
}
@property(retain) IBOutletCollection(UILabel) NSArray *statPanels;
@end

.m

@interface ViewController ()
@end

@implementation ViewController
@synthesize statPanels;

- (void)viewDidLoad
{
    [super viewDidLoad];

    statPanels = [[NSArray alloc] initWithObjects:[UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], nil ];

    [statPanels objectAtIndex:3].hidden = YES;
}

Solution

  • If you connected all of the labels in interface builder then you don't have to initialize the statPanels array.

    Delete this line:

    statPanels = [[NSArray alloc] initWithObjects:[UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], nil ];
    

    That line is creating a new array and a bunch of new labels, and losing your outlets.

    Also, you will need to cast like the other answer is saying:

    ((UILabel *) [statPanels objectAtIndex:3]).property = ....