如何在Objective C中全局访问此变量?

时间:2011-07-07 10:54:31

标签: objective-c ios xcode ios4

以下代码我遇到了以下问题:

if(DriveInfoDict) {
    NSLog(@"%@", DriveInfoDict);
    //PrevSpeedsDict = [DriveInfoDict objectForKey: @"speed"];
    //NSLog(@"Previous Speed Dict:%@", PrevSpeedsDict);
}



DriveInfoDict = [NSDictionary dictionaryWithObjectsAndKeys:
                 [NSNumber numberWithDouble: CurrentLatitude], @"Lat",
                 [NSNumber numberWithDouble: CurrentLongitude], @"Long",
                 [NSNumber numberWithDouble:speedMPH], @"speed",
                 nil];  

在这里,我想设置DriveInfoDict,以便下次运行该函数时它将具有前一个值。我剥离了操作员以简化我的问题。

我得到的错误是:EXC-BAD-ACCESS

我是Obj-C的新手,我不知道如何在这里访问这个对象。一些代码解释了它是否属于H或M文件将非常有用。

1 个答案:

答案 0 :(得分:3)

您需要保留字典或使用alloc/init(返回保留字典。所以:

DriveInfoDict = [[NSDictionary dictionaryWithObjectsAndKeys:
                 [NSNumber numberWithDouble: CurrentLatitude], @"Lat",
                 [NSNumber numberWithDouble: CurrentLongitude], @"Long",
                 [NSNumber numberWithDouble:speedMPH], @"speed",
                 nil] retain];

或:

DriveInfoDict = [[NSDictionary alloc] initWithObjectsAndKeys:
                 [NSNumber numberWithDouble: CurrentLatitude], @"Lat",
                 [NSNumber numberWithDouble: CurrentLongitude], @"Long",
                 [NSNumber numberWithDouble:speedMPH], @"speed",
                 nil];

如果替换DriveInfoDict的内容(即:分配新词典),请不要忘记先发布它。