简体   繁体   English

iOS,无法在viewDidLoad之外进行委托

[英]iOS, Unable to delegate outside of viewDidLoad

I have this appdelegate.h 我有这个appdelegate.h

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

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

and the .m file 和.m文件

@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.. 现在...我想从另一个控制器获取这个名称,如果我尝试在我的viewDidLoad方法中调用它,它就可以工作。

- (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... 但是如果我尝试在initWithNibName中做同样的事情,那将是行不通的...

- (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 ); 如果要覆盖-initWithNibName:需要返回该类的实例(或self ); Try the following code in -initWithNibName: . -initWithNibName:尝试以下代码-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. 我认为这可能对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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