gpt4 book ai didi

iOS,无法委托(delegate)viewDidLoad之外

转载 作者:行者123 更新时间:2023-11-29 04:34:42 25 4
gpt4 key购买 nike

我有这个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;
}

现在......我想从另一个 Controller 获取这个名称,如果我尝试在我的 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: 中尝试以下代码。它对我有用。

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

我认为这可能对你有用。

关于iOS,无法委托(delegate)viewDidLoad之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11219323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com