Question

I'm getting a bit confused with UIViews recently, I have been using them fine up until this point and they are just refusing to be compliant!

I have a UIViewController, and this contains 5 different views. I have created IBOutlets for these views as I am wanting to swap them at runtime:

IBOutlet UIView *view1;
IBOutlet UIView *view2;
IBOutlet UIView *view3;
IBOutlet UIView *view4;
IBOutlet UIView *view5;

To make them easier to maintain I decided to keep them all within an array, called viewArray. Now I am trying to add the views to the array as follows:

viewArray = [NSArray arrayWithObjects:view1, view2, view3, view4, nil];

This is being called in the init function of my UIViewController class. I have linked up all the IBOutlets to their relevant views in the xib / interface file, but they do not appear to be initialized. Upon further debugging it looks like the views aren't initialized until after the init function is called?

So how can I create an array of these objects? I will need to select the relevant view before the view itself is shown, therefore viewDidLoad is not an option.

I know that you can grab the tags of things and implicitly set them using:

imageExample = (UIImageView *)[self.view viewWithTag:100];

But can this be used to find views, as surely it will be searching for the tags within the originally initialized view (view1)?

Thanks for any help in advanced, Kind Regards, Elliott

Was it helpful?

Solution

You can initialize the viewArray lazily, for the price of having to use self.viewArray instead of unqualified viewArray.

Here is how you can do it:

In the .h file:

NSArray* _viewArray;

@property (nonatomic, readonly) NSArray *viewArray;

In the .m file:

-(NSArray*) viewArray {
    if (!_viewArray) {
        _viewArray = [NSArray arrayWithObjects:view1, view2, view3, view4, nil];
    }
    return _viewArray;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top