简体   繁体   中英

Accessing interface builder object from view controller

I'm completely new to Objective-C, XCode, and iOS development and I'm trying to figure out how to run certain code at startup, after all UI views and controls have been instantiated. I have a generic NSObject that I've added through interface builder by dragging it into my view controller scene. It's defined as follows:

#import <Foundation/Foundation.h>

@interface Controller : NSObject {
    IBOutlet UISlider *slider;        
    IBOutlet UILabel *label;
}

-(IBAction)sliderChanged:(id)sender;

@end

I need to run sliderChanged on initialization. I've tried the following way:

#import "Controller.h"

@implementation Controller

-(id)init {
    self = [super init];
    if (self){
        [self sliderChanged:nil];
    }
    return self;
}
// More code here

But both my slider and label are nil when this is called. I understand there's a viewDidLoad method within the ViewController class which may be what I need, but I'm not sure how to access the instance of my Controller class (which seems to be instantiated somewhere behind the scenes by the interface builder) from within that method. Should all of this code simply be moved to the ViewController itself? That would seem to make sense, but the design above is what we've been instructed in class, so I'm not really sure how to go about doing this.

After the XIB/Storyboard loader finishes loading all the objects and wiring them up, it sends awakeFromNib to every object that was instantiated from the XIB. So try adding this to your Controller class:

- (void)awakeFromNib {
    [super awakeFromNib];
    [self sliderChanged:nil];
}

You can find more information in the NSObject UIKit Additions Reference and “The Nib Object Life Cycle” in the Resource Programming Guide .

HOWEVER , if you created Controller as a top-level object, and you didn't connect any outlets to it, then nothing references it after the XIB loader finishes with it, so the system will deallocate it again. That's probably not what you want, so you should connect an outlet in your view controller to the Controller . If you do that (and let's say the outlet is named controller ), then you can access it in viewDidLoad in your view controller class:

#import <UIKit/UIKit.h>
#import "Controller.h"

@interface ViewController : UIViewController {
    IBOutlet Controller *controller;
}
@end

Implementation:

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.controller sliderChanged:self];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM