0

我的项目中有一个 App Delegate 和 3 个视图控制器。我的 App Delegate 中有一个变量(一个 NSMutable 数组),我想从我的视图控制器访问它。所以我决定创建一个指向我的 App Delegate 的指针并访问变量。这是我的代码:

iSolveMathAppDelegate.h

#import <UIKit/UIKit.h>

@interface iSolveMathAppDelegate : NSObject <UIApplicationDelegate> {

    UIWindow *window;
    UITabBarController *tabBarController;
    NSMutableArray *tmpArray;
    }


@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) NSMutableArray *tmpArray; // variable I want to access
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;

@end

iSolveMathAppDelegate.m

#import "iSolveMathAppDelegate.h"


@implementation iSolveMathAppDelegate

@synthesize window;
@synthesize tabBarController;
@synthesize tmpArray;
...
- (void)dealloc {
    [tabBarController release];
    [window release];
    [tmpArray release];
    [super dealloc];
}


@end

我要从中访问 tmpArray 的视图控制器类。

参考视图控制器.h

#import <UIKit/UIKit.h>

@class iSolveMathAppDelegate;

@interface referenceViewController : UITableViewController {
    NSMutableArray *equationTypes;
    iSolveMathAppDelegate *data;

}

@property(nonatomic, retain) NSMutableArray *equationTypes;
@property(nonatomic, retain) iSolveMathAppDelegate *data;

@end

最后参考ViewController.m

#import "referenceViewController.h"


    @implementation referenceViewController
    @synthesize equationTypes, data;

     data = (iSolveMathAppDelegate *)[[UIApplication sharedApplication] delegate]; 
//says that initializer element is not constant...ERROR!




        - (void)viewDidLoad {
            [super viewDidLoad];

        NSString *path = [[NSBundle mainBundle] pathForResource:@"equationTemplates"ofType:@"plist"];
        data.tmpArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
        self.equationTypes = data.tmpArray;
  [data.tmpArray release]; // obviously none of these work, as data is not set.

    }


    - (void)dealloc {
        [super dealloc];
        [equationTypes release];
        [data release];
    }


    @end

所以无论如何 data = (iSolveMathAppDelegate *)[[UIApplication sharedApplication] delegate];编译器都会说初始化元素不是常量。

我已经在网上寻找答案,而且它似乎工作......但对我来说没有骰子:(你能告诉我我哪里出错了吗?我正在使用 XCode 3.2 和 iOS SDK 3......也许SDK是问题所在。

谢谢你

4

2 回答 2

2

那行代码不在方法或函数中,因此编译器将其视为编译时常量或静态/全局变量的定义。那些需要用于初始化的常量值。

您应该将赋值data放在一个方法中。一个好地方是-viewDidLoad

- (void)viewDidLoad {
    [super viewDidLoad];

    data = (iSolveMathAppDelegate *)[[UIApplication sharedApplication] delegate]; 

    ...
}
于 2011-03-23T00:38:58.013 回答
0

我弄清楚了结构和联合问题。我所要做的就是更改@class iSolveAppDelegate#import "iSolveAppDelegate.h"的referenceViewController.h 文件。感谢乔纳森的帮助!

于 2011-03-23T03:07:37.787 回答