Eth*_*ick 2 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];
}
Run Code Online (Sandbox Code Playgroud)
初始化字典并向其添加内容工作正常,但在另一个类中.
#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];
}
Run Code Online (Sandbox Code Playgroud)
您可以看到我尝试再次为此类初始化字典,但这显然无效.我只想在AppDelegate文件中初始化并设置一次字典,然后从其他类中访问该字典以更改其中的内容.有没有办法做到这一点?
使您的NSMutableDictionary实例静态并编写一个类方法来访问它.把它放在你的SheepAppDelegate.m中:
static NSMutableDictionary *theHeart;
+ (NSMutableDictionary*)theHeart
{
if (theHeart == nil) theHeart = [[NSMutableDictionary alloc] init];
return theHeart;
}
Run Code Online (Sandbox Code Playgroud)
并使用以下方式访问其他任何地方:
NSMutableDictionary *dict = [SheepAppDelegate theHeart];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2870 次 |
| 最近记录: |