2011-07-07 55 views
1

這裏是遇到問題的代碼IM:如何在Objective C中全局訪問這個變量?

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文件將是非常有用的。

回答

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的內容(即:分配一本新字典)別忘了先發布它

+0

非常感謝您先生 – TaylorMac

+0

當它允許時 – TaylorMac