我有这个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:
中尝试以下代码。它为我工作。
- (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 - iOS,无法在viewDidLoad之外进行委托(delegate),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11219323/