2011-04-28 45 views
1

我必須在我的程序中使用NSDate var,並且該var將是dealloc和realloc(我必須在此日期添加一些月份和年份,並且沒有其他可能性)。static var or AppDelegate

該var必須是許多方法中的用戶,我想把這個var放在全局中。還有其他的選擇嗎?這不是乾淨的,但我不知道如何以其他方式做...

非常感謝您的幫助!

回答

1

我建議把它放到你的AppDelegate中。然後你可以通過

MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate]; 
NSLog(@"%@", [appDelegate myGlobalDate]); 

當然,你需要getter和setter myGlobalDate在MyAppDelegate。

+1

我反對這種做法。不要讓應用程序委託成爲「主超級管理員」類。在那裏,做到了,從中吸取了教訓。 :) – Eiko 2011-04-28 15:43:52

+1

不要讓你的應用程序代表亂七八糟。 – Till 2011-04-28 15:44:37

+2

好的,請讓我們知道你從這個錯誤中學到了什麼。 – dasdom 2011-04-28 15:45:05

1

想想這個變量有什麼用途,以及最經常使用它的地方。那麼你應該找到一個自然的地方。

全局變量並不是絕對可怕的,也不是單身人士(其中可能在這裏很合適)。但是,可能它確實屬於用戶默認設置或某個視圖控制器。

+0

感謝您指出它。 – dasdom 2011-04-28 15:50:40

1

回答關於是否有其他選項的問題(而不是談論是否應該這樣做)。一種選擇是專門製作一個班級作爲保存變量的地方,您需要在全球範圍內提供這些變量。從這個blog post

@interface VariableStore : NSObject 
{ 
    // Place any "global" variables here 
} 
// message from which our instance is obtained 
+ (VariableStore *)sharedInstance; 
@end 

@implementation VariableStore 
+ (VariableStore *)sharedInstance 
{ 
    // the instance of this class is stored here 
    static VariableStore *myInstance = nil; 

    // check to see if an instance already exists 
    if (nil == myInstance) { 
     myInstance = [[[self class] alloc] init]; 
     // initialize variables here 
    } 
    // return the instance of this class 
    return myInstance; 
} 
@end 

然後一個例子,從其他地方:

[[VariableStore sharedInstance] variableName] 

當然,如果你不喜歡他們實例化在上面的例子中單的方式,你可以選擇自己喜歡的pattern from here 。我喜歡dispatch_once模式,我自己。