0

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

任何人都可以帮助我吗?这个问题快把我逼疯了...

4

1 回答 1

1

如果要覆盖-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;
}

我认为这可能对你有用。

于 2012-06-27T06:45:11.850 回答