I’m trying to hide an object in my viewController, with code executed from a custom class, but the object is nil.
FirstViewController.h
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController {
IBOutlet UILabel *testLabel;
}
@property (nonatomic, retain) IBOutlet UILabel *testLabel;
- (void) hideLabel;
FirstViewController.m
I synthesize testLabel and I have a function to hide it. If I call the function from viewDidAppear it works, but I want to call it from my other class. When called from the other class, testLabel is nil
#import "FirstViewController.h"
#import "OtherClass.h"
@implementation FirstViewController
@synthesize testLabel;
- (void) hideLabel {
self.testLabel.hidden=YES;
NSLog(@"nil %d",(testLabel==nil)); //here I get nil 1 when called from OtherClass
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
OtherClass *otherClass = [[OtherClass alloc] init];
[otherClass hideThem];
//[self hideLabel]; //this works, it gets hidden
}
OtherClass.h
@class FirstViewController;
#import <Foundation/Foundation.h>
@interface OtherClass : NSObject {
FirstViewController *firstViewController;
}
@property (nonatomic, retain) FirstViewController *firstViewController;
-(void)hideThem;
@end
OtherClass.m
calls the hideLabel function in FirstViewController. In my original project, (this is an example obviously, but the original project is at work) I download some data here and I want to hide my loading label and indicator when download is done
#import "OtherClass.h"
#import "FirstViewController.h"
@implementation OtherClass
@synthesize firstViewController;
-(void)hideThem {
firstViewController = [[FirstViewController alloc] init];
//[firstViewController.testLabel setHidden:YES]; //it doesn't work either
[firstViewController hideLabel];
}
Any ideas?
Your
UILabelis nil because you just initialized your controller but didn’t load it’s view. Your controller`s IBoutlets are instantiated from the xib or storyboard automatically when you ask access to the bound view for the first time, so in order to access them you first have to load its view by some means.EDIT (after OP comments):
Since your
FirstViewControlleris already initialized and yourOtherClassis instantiated by that controller, you could just hold a reference to it and not try to initialize a new one.So try something like this:
In your OtherClass.m: