繁体   English   中英

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

[英]iOS, Unable to delegate outside of viewDidLoad

我有这个appdelegate.h

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

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

和.m文件

@synthesize name;

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

    name=@"john";
    return YES;
   }

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

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

但是如果我尝试在initWithNibName中做同样的事情,那将是行不通的...

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

有人可以帮我吗? 这个问题使我发疯...

如果要覆盖-initWithNibName:需要返回该类的实例(或self ); -initWithNibName:尝试以下代码-initWithNibName: 它为我工作。

- (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;
}

我认为这可能对您有用。

暂无
暂无

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

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