2009-11-11 93 views
2

在我的iPhone應用程序中,我使用整數來跟蹤很多變量。我在我的AppDelegate文件(它是一個多視圖應用程序)中聲明並初始化它們,然後如果我在其他視圖(類)中聲明它們並且值將保持不變。通過這種方式,我可以在App Delegate文件中設置Money = 200,然後在另一個視圖中聲明「int Money」。並且它已經設置爲200(或者其他任何Money)從不同的類訪問NSMutableDictionary

但是,如果我將所有這些變量存儲在字典中(我現在正在這樣做),如何從不同的字典中訪問該字典類/看法?我不能簡單地「再次申報」,我已經試過了。我認爲它與作爲對象的字典有關,因此它需要被引用或者其他東西。

我需要能夠從所有不同的視圖訪問相同的詞典。

#import "SheepAppDelegate.h" 

@implementation SheepAppDelegate 

@synthesize window; 
@synthesize rootController; 

//Initialize the Dictionary to store all of our variables 

NSMutableDictionary *theHeart; 



- (void)applicationDidFinishLaunching:(UIApplication *)application {  

    //Set the values for the Variables and Constants, these are 
    //accessed from the different classes. 

    NSMutableDictionary *theHeart = [[NSMutableDictionary alloc] init]; 


    [theHeart setObject:[NSNumber numberWithInt:200] forKey:@"Money"]; 
    [theHeart setObject:@"Number two!" forKey:@"2"]; 


    [window addSubview:rootController.view]; 
    [window makeKeyAndVisible]; 
} 

初始化字典並添加東西到它工作正常,但在另一個類。

#import "OverviewController.h" 

@implementation OverviewController  

@synthesize lblMoney; 
@synthesize lblSheep; 
@synthesize lblWool; 
@synthesize lblFatness; 
@synthesize lblCapacity; 
@synthesize lblShepherds; 

int varMoney; 

NSMutableDictionary *theHeart; 

- (void)viewWillAppear:(BOOL)animated {  
    varMoney = [[theHeart objectForKey:@"Money"] intValue]; 
} 

你可以看到我嘗試再次爲這個類初始化字典,但顯然不工作。我只想在AppDelegate文件中初始化並設置字典一次,然後從其他類訪問該字典以更改其中的內容。有沒有辦法做到這一點?

回答

6

使您的NSMutableDictionary實例爲靜態,並編寫一個類方法來訪問它。把這個在您的SheepAppDelegate.m:

static NSMutableDictionary *theHeart; 
+ (NSMutableDictionary*)theHeart 
{ 
    if (theHeart == nil) theHeart = [[NSMutableDictionary alloc] init]; 

    return theHeart; 
} 

,並通過使用其他任何地方訪問它:

NSMutableDictionary *dict = [SheepAppDelegate theHeart]; 
2

你可以把它放在你的AppDelegate中或創建一個Singleton。 This article涵蓋了這個主題和許多可能的選項,包括我提到的兩個選項。

單身人士似乎是更有組織的方法。您可以將所有全局信息存儲在一箇中,並且您可以從任何地方訪問它。

2

有沒有很好的理由不只是把字典一起到控制器作爲參考。如果您在OverviewController中創建一個NSMutableDictionary ivar,使其成爲一個屬性,那麼可以在創建控制器或從nib解凍時設置字典。

單身是有用的,但我不會訴諸它,除非你真的需要它。您可以將您-applicationDidFinishLaunching改變這樣的事情:

- (void)applicationDidFinishLaunching:(UIApplication *)application {  

    //Set the values for the Variables and Constants, these are 
    //accessed from the different classes. 

    NSMutableDictionary *theHeart = [NSMutableDictionary dictionary]; 

    [theHeart setObject:[NSNumber numberWithInt:200] forKey:@"Money"]; 
    [theHeart setObject:@"Number two!" forKey:@"2"]; 

    [rootController setHeartDictionary:theHeart]; 

    [window addSubview:rootController.view]; 
    [window makeKeyAndVisible]; 
} 

這裏假設你的rootController是類型OverviewController的。然後在您的OverviewController標題中,您應該聲明如下屬性:

@property(assign)NSMutableDictionary * heartDictionary;

然後@synthesize它在.m文件中使用@synthesize heartDictionary ;.

同樣,我不會使用單例,除非你需要它。相反,將它作爲變量傳遞給您的控制器。