如何从自定义控制器操作引用AppDelegate实例变量?

时间:2011-02-21 06:44:12

标签: iphone ios4 uiviewcontroller interface-builder

我希望能够(作为控制器的学习练习)在我设置的初始视图上有一个按钮,然后如果单击该按钮,会发生一个动作,将视图从视图1切换到视图2.我是不知道你怎么这样?请参阅下面代码中我想要放入代码的部分。

可以发布我需要的代码吗? (即,它将涵盖如何引用我在AppDelegate中建立的变量)。让我知道,如果我给自己做的这种练习在某个地方有缺陷。感谢。

AppDelegate * .h

#import <UIKit/UIKit.h>
@class gregsController;
@class Gregs2ndController;  

@interface windowsBasedAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    gregsController *viewController;
    Gregs2ndController *view2Controller;

}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet gregsController *viewController;
@property (nonatomic, retain) IBOutlet Gregs2ndController *view2Controller;

@end

AppDelegate * .m

#import "windowsBasedAppDelegate.h"
#import "gregsController.h"
#import "Gregs2ndController.h"

@implementation windowsBasedAppDelegate

@synthesize window;
@synthesize viewController;
@synthesize view2Controller;

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

    // Override point for customization after application launch.
    NSLog(@"windowsBasedAppDelegate - didFinishLaunchingWithOptions");

    //[self.window addSubview:viewController.view];
    [self.window addSubview:view2Controller.view];
    [self.window makeKeyAndVisible];

    return YES;
}

自定义控制器* .m

#import "gregsController.h"
@implementation gregsController
- (IBAction)logSomething {
    NSLog(@"About to switch views");
    [self.view removeFromSuperview];

        // *** HOW DO I REFERENCE view2Controller AND PUT THIS AS THE VIEW  ???? ****

    NSLog(@"Finished switching views");
}

3 个答案:

答案 0 :(得分:7)

您可以通过UIApplication单身人士随时随地获取对您的应用代表的引用:

#import "gregsController.h"
@implementation gregsController
- (IBAction)logSomething {
    NSLog(@"About to switch views");
    [self.view removeFromSuperview];

    // *** HOW DO I REFERENCE view2Controller AND PUT THIS AS THE VIEW  ???? ****
    // Like this:
    windowsBasedAppDelegate* appDelegate = (windowsBasedAppDelegate*)[[UIApplication sharedApplication] delegate];
    [appDelegate.window addSubview:appDelegate.view2Controller.view];

    NSLog(@"Finished switching views");
}

答案 1 :(得分:1)

获取在app delegate中创建的变量的引用

testAppDelegate * appDelegate =(testAppDelegate *)[[UIApplication sharedApplication] delegate];

从app delegate引用任何变量,例如你可以使用

appDelegate .view2Controller

答案 2 :(得分:1)

您可以访问您的应用代理并更改此视图:

#import "windowsBasedAppDelegate.h"

windowsBasedAppDelegate *delegate = (windowsBasedAppDelegate *) [[UIApplication sharedApplication] delegate];
view2Controller *view_controller = delegate.view2Controller;

[window addSubView:view_controller.view];
[window becomeKeyWindow];