2012-05-24 13 views
1

我聲明變量NSString productname在appdelegate中,並從視圖中指定值appdelegate.productname = name。然後我嘗試從另一個view.lbl.text=appdelegate.productname中獲取此值。這是錯誤的嗎?如何在視圖中使用appdelegate變量

回答

0

您可以使用此代碼得到它:

UIApplicationDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; 
NSString *productName = appDelegate.productname; 
+0

它顯示錯誤使用未聲明的標識符uiapplicationdelegate – user1395474

+0

UIApplicationDelegate在這裏我提到了你的項目的應用程序委託類的名稱。 #將您的項目的appdelegate類導入您的視圖控制器。 – vtechig

0
UIApplicationDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; 
NSString * str = appDelegate.yourstr; 
+0

你能解釋爲什麼這段代碼有用嗎? – 2012-06-14 11:57:48

2

您可以在appdelegate.h文件中聲明的變量,這些變量是全局你不需要做的appdelegate對象來調用它們。

這樣的 -

#import <UIKit/UIKit.h> 

@class ViewController; 

// these are your variable, both are global. 
int anyNumber; 
NSString *productname; 

@interface AppDelegate : UIResponder <UIApplicationDelegate> 

@property (strong, nonatomic) UIWindow *window; 
@property (strong, nonatomic) ViewController *viewController; 
@property (strong, nonatomic) UINavigationController *naviCon; 

@end 

現在,你可以在任何地方,你想用使用這些變量。

只需導入appdelegate.h並自由使用它。

#import "ViewController.h" 
#import "AppDelegate.h" 

這是您將第一個視圖指定給appdelegate字符串的值。

productname = name; //you can assign it directly, no need to make any object of appdelegate. 

現在你可以在任何地方使用它。但請記住你必須導入的小東西

#import "AppDelegate.h" 

在你的viewcontroller。

謝謝!

相關問題