我在我的項目中有一個App Delegate和一個3視圖控制器。我在我的應用程序委託中有一個變量(一個NSMutable Array),我想從我的視圖控制器訪問它。所以我決定創建一個指向我的App Delegate的指針並訪問變量。 這裏是我的代碼:雖然引用AppDelegate時出錯
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的問題。
謝謝
嗨,感謝您的及時回覆。這當然有效。但是,當我嘗試通過去data.tmpArray來訪問tmpArray時,我得到一個錯誤代碼,我要求tmpArray不是結構體或聯合體。你能幫我解決嗎?再一次感謝你。 – Aravind 2011-03-23 01:02:51
導入應用程序委託的標題。如果你不這樣做,那麼編譯器將不知道它聲明瞭什麼屬性。 – 2011-03-23 12:20:53