Search code examples
iosobjectviewdidload

iOS, Unable to delegate outside of viewDidLoad


I have this appdelegate.h

#import <UIKit/UIKit.h>
@interface appDelegate : NSObject <UIApplicationDelegate> {
  UIWindow *window;
  NSString *name;

}
@property (nonatomic, retain) NSString *name;
@end

and the .m file

@synthesize name;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    name=@"john";
    return YES;
   }

Now...I want to get this name from another controller, if I try to call it inside my viewDidLoad methods, it works..

- (void)viewDidLoad
{
    appDelegate *test= (appDelegate *)[[UIApplication sharedApplication] delegate];
    NSLog(@"%@", test.name);
}

but If I try to do the same thing in my initWithNibName it just didn't work...

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    {
        appDelegate *test= (appDelegate *)[[UIApplication sharedApplication] delegate];
        NSLog(@"%@", test.name);
    }

Anyone can help me out? This problem is driving me crazy...


Solution

  • If you are overriding the -initWithNibName:, you need to return an instance of the class (or self); Try the following code in -initWithNibName:. It is working for me.

    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    {
        appDelegate *test= (appDelegate *)[[UIApplication sharedApplication] delegate];
        NSLog(@"%@", test.name);
    
       if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
    
       }
       return self;
    }
    

    I think this may useful to you.