简体   繁体   中英

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...

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.

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