引用AppDelegate时出错

时间:2011-03-23 00:34:00

标签: iphone xcode elements viewcontroller uiapplicationdelegate

我的项目中有一个App Delegate和一个3视图控制器。我的App Delegate中有一个变量(一个NSMutable Array),我想从我的视图控制器访问它。所以我决定创建一个指向我的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的视图控制器类。

referenceViewController.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

最后是referenceViewController.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就是问题。

谢谢

2 个答案:

答案 0 :(得分:2)

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

您应该将data的分配放在方法中。一个好地方是-viewDidLoad

- (void)viewDidLoad {
    [super viewDidLoad];

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

    ...
}

答案 1 :(得分:0)

我想出了结构和联合问题。我所要做的就是在referenceViewController.h文件中将@class iSolveAppDelegate更改为#import "iSolveAppDelegate.h"。感谢Jonathan的帮助!