2011-11-26 104 views
1

可能重複:
How to use global variables in Objective-C?在Objective-C全局字符串變量

在我Login.m文件,我有

NSString *userName = txtUsername.text; // this is getting the text from the username text field and storing it in userName 

的問題是,我需要訪問來自不同類的變量userName,所以我需要將其聲明爲全局變量。這樣做的最好方法是什麼?

+0

這個問題從[XY問題]遭受(http://meta.stackexchange.com/questions/ 66377 /)。至於它描述的解決方案,[globals are bad](http://c2.com/cgi/wiki?GlobalVariablesAreBad)。作爲替代方法,請參閱[Objective-C:在一個線程中進行分配並在其他版本中進行分配](http://stackoverflow.com/q/4698273/90527),以獲取帶訪問器的類變量的示例實現。 – outis

回答

1

一種選擇是使其成爲應用程序委託中的實例變量。應用程序委託可以很容易地從其他類實例中訪問。由於全局變量不是一個好的設計,這有點更好。

0

我會做的是忘記變量,但在這些其他類中引用txtUsername.txt,否則你正在製作一個你試圖保持更新的文本的副本,希望你沒有錯過任何東西。

所以在你的.h文件中,你把

{ 

UITextField *txtUsername; 

} 

,我假設你已經有了。

然後:

@property (nonatomic, retain) UITextField *txtUsername; 

,然後在.m文件,在上面放,在@implementation線下:

@synthesize txtUsername; 

然後在.m文件要引用它在,去它的.h文件,並把:

#import "Login.h" 

頂部,與其他進口線。然後輸入:

{ 

Login *login; 

} 

這會創建一個名爲login的變量。如果你使用的是xib,那麼你可以將它連接到你的xib,或者如果你沒有使用代碼初始化它。然後,當你想要的文字,你簡單地說:

login.txtUsername.text; 
+0

嗨,我這樣做,但我得到一個錯誤信息 - 使用未聲明的標識符'登錄' –

0

考慮一個singleton類將持有你的全局變量。

要聲明一個單獨的類,看看下面的例子和,或見here

+(Constants *) instance { 
    @synchronized(self) { 
     if (gInstance == NULL) { 
      gInstance = [[self alloc] init]; 
     } 
    } 

    return gInstance; 
} 


-(id) init { 

    if (gInstance != NULL) { 
     return gInstance; 
    } 

    self = [super init]; 

    if (self) { 
     // do something clever 
    } 
    gInstance = self; 
    return gInstance; 
}