NSMutableDictionary从不同的类访问

时间:2009-11-11 20:18:06

标签: iphone objective-c nsmutabledictionary

在我的iPhone应用程序中,我使用整数来跟踪很多变量。我在我的AppDelegate文件中声明并初始化它们(它是一个多视图应用程序),然后如果我在其他视图(类)中声明它们并且值保持不变。这样,我可以在App Delegate文件中设置Money = 200,然后在另一个视图中声明“int Money;”并且它已经设置为200(或者不管是什么钱。)

但是,如果我将所有这些变量存储在一个Dictionary中(我现在正在做),我如何从不同的类/视图中访问该字典?我不能简单地“再宣布”它,我已经尝试过了。我认为它与字典是一个对象有关,因此需要引用它或其他东西。

我需要能够从所有不同的视图中访问相同的字典。

#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文件中初始化并设置一次字典,然后从其他类中访问该字典以更改其中的内容。有没有办法做到这一点?

3 个答案:

答案 0 :(得分:6)

使您的NSMutableDictionary实例静态并编写一个类方法来访问它。把它放在你的SheepAppDelegate.m中:

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

    return theHeart;
}

使用以下方法在其他地方访问:

NSMutableDictionary *dict = [SheepAppDelegate theHeart];

答案 1 :(得分:2)

您可以将其放入AppDelegate或创建Singleton。 This article涵盖了这个主题以及许多可能的选项,包括我提到的两个选项。

单身人士似乎是更有条理的方法。您可以将所有全局信息存储在一个中,并且您可以从任何地方访问它。

答案 2 :(得分:2)

没有充分的理由不将字典作为参考传递给您的控制器。如果在OverviewController中创建一个NSMutableDictionary ivar,使其成为属性,则可以在创建控制器或从笔尖解冻时将字典设置在那里。

单身人士很有用,但除非你真的需要,否则我不会诉诸它。您可以将-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;。

同样,除非你需要,否则我不会使用Singleton。将其作为变量传递给控制器​​。