6

dogビューコントローラがアプリデリゲートでアクセスできるようにしたいと思います。

アプリデリゲートがViewControllerでアクセスできるようにしたいと思いますmouse


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    int mouse;  // <----------------
}
@end

- (void)viewDidLoad
{
    [super viewDidLoad];

    mouse = 12;  // <-------------------

    NSLog(@"viewDidLoad %d", dog); // <---------------
}

#import <UIKit/UIKit.h>

@class ViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    int dog;  // <---------------
}
@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController *viewController;

@end

- (void)applicationWillResignActive:(UIApplication *)application
{
    NSLog(@"applicationWillResignActive %d", mouse); // <--------------
}

 - (void)applicationDidBecomeActive:(UIApplication *)application
{
    dog = 77; // <---------------------

    NSLog(@"applicationDidBecomeActive");
}
4

2 に答える 2

8

パート1:ViewController.h内:

-(int)mouse;  //add this before the @end

ViewController.mに、次のメソッドを追加します。

-(int)mouse
{
    return mouse;
}

AppDelegateからマウスにアクセスするには、self.viewController.mouseを使用します。例:

NSLog(@"ViewController mouse: %i", self.viewController.mouse);

パート2:

AppDelegate.hの場合:

-(int)dog;  //add this before the @end

AppDelegate.mで、次のメソッドを追加します。

-(int)dog
{
    return dog;
}

ViewController.mの場合:

#import "AppDelegate.h"

ViewControllerからdogにアクセスするには、次を使用します。

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(@"dog from AppDelegate: %i", [appDelegate dog]);  //etc.
于 2012-05-03T18:11:37.387 に答える
6

ビューコントローラのヘッダーファイルで、プロパティとしてマウスを追加します。

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    NSInteger mouse;  // <----------------
}

@property (nonatomic, assign) NSInteger mouse;

@end

@implementation行のすぐ下にあるViewController実装のプロパティを合成します。

@synthesize mouse;

アプリのデリゲートで、プロパティとして犬を追加します。

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    NSInteger dog;  // <---------------
}
@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController *viewController;

@property (nonatomic, assign) NSInteger dog;

@end

また、アプリデリゲートの実装でdogを合成します。

これで、アプリデリゲートで、View Controllerへの参照があると仮定して、次のようにマウスにアクセスできます。

viewController.mouse = 13;

アプリデリゲートクラスでも同じことができます。アプリデリゲートクラスには、次を使用して任意のビューコントローラーからアクセスできます(アプリデリゲートクラスの名前がAppDelegateであると想定)。

((AppDelegate *)([UIApplication sharedApplication].delegate)).dog = 13;

intの代わりにNSIntegerも使用することをお勧めします。

于 2012-05-03T18:16:43.693 に答える