2009-11-11 91 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 ;.

同样,我不会使用单例,除非你需要它。相反,将它作为变量传递给您的控制器。