2010-12-11 129 views
0

我想設置一個布爾值。我可以成功地設置它,但是,在另一個班級中,所反映的變化不會顯示出來。外部變量不更新

下面是一個例子:

File1中:

@implementation ClassOne //UIViewController 

extern BOOL theValue; 

- (void)loadFile { 
    theValue = YES; 
} 
... 
@end 

文件2:

@implementation ClassTwo //UIViewController 
BOOL theValue; 
- (void)switchValueChanged { 
    theValue = NO; 
} 


@end 

我initally設置在一個類中的值,用YES的初始值。但是,當我將ClassTwo中的值設置爲NO並返回到ClassOne時,該值仍爲YES。

我有點卡住了。你會認爲它會更新。但事實並非如此。

任何幫助表示讚賞。完成你所追求的

+0

也許會顯示一些更多的代碼和它的確切位置,即什麼方法等。 – Eiko 2010-12-11 09:52:52

回答

0

我想通了。當我的應用程序啓動時,它默認將值設置爲YES。問題在於我爲此使用了一個viewWillAppear:animated方法,並且每次ClassTwo的視圖被解除時,viewWillAppear:animated方法被調用,並且被設置的值已被重置。我改變了方法viewDidLoad和一切工作正常。

0

最簡單的方法是聲明BOOL在你的appDelegate的接口文件:

@interface AppDelegate : .... 
{ 
    BOOL theValue; 
} 

@property BOOL theValue; 
從ClassOne

然後或ClassTwo你可以得到/直接通過設置變量:

MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate]; 
appDelegate.theValue = YES; 

OR

如果你真的想訪問全球,只需聲明變量@interface ... @end

BOOL theValue 
@interface AppDelegate : ... 
{ 
... 
} 

然後你就可以通過簡單地導入AppDelegate的頭文件訪問變量theValue從你的代碼的任何地方:

#import "AppDelegate.h" 
@implementation ClassOne : .... 
... 
theValue = YES; 
+0

他已經使用extern作爲全局變量......至少這就是代碼所暗示的。 – Eiko 2010-12-11 09:52:05

+0

@Eiko你是對的,我錯過了那一點。相應地編輯我的答案。 – Rog 2010-12-11 09:58:41

+0

我嘗試了這兩種方法...似乎沒有工作... – 2010-12-11 10:33:13