2011-08-18 88 views
2

我無法將字典添加到nsmutabledictionary。任何人都可以看到我做錯了什麼?將條目添加到NSMutableDictionary

@interface viewMap : UIViewController<MKMapViewDelegate> { 

    NSMutableDictionary *onclickDic; 

} 

@property (nonatomic, retain) NSMutableDictionary *onclickDic; 
@end 

@implementation viewMap 
@synthesize onclickDic; 

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation { 

    NSString *pushLat = [NSString stringWithFormat:@"%f", [annotation coordinate].latitude]; 
    NSString *pushLng = [NSString stringWithFormat:@"%f", [annotation coordinate].longitude]; 

    NSDictionary *latlngDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:pushLat, pushLng, nil] forKeys:[NSArray arrayWithObjects:@"lat", @"lng", nil]]; 

    NSDictionary *toPush = [NSDictionary dictionaryWithObject:latlngDic forKey:[NSString stringWithFormat:@"%i", i]]; 


    NSLog(@"toPush is %@", toPush); // this one is correct and works 

    [self.onclickDic addEntriesFromDictionary:toPush]; 

    NSLog(@"onclickDic is %@", onclickDic); // this one gives (null) 
} 
@end 
+1

「遇到的麻煩」沒有一些更多的信息是一個問題。究竟出了什麼問題?如果有錯誤信息,它是什麼,錯誤發生在哪裏? –

+0

@Rudy Velthuis謝謝你的回答。下面的答案幫了我。我忘了alloc/init並釋放對象clickDic – Melvin

+0

不過,下一次有問題時,請提供更多信息。人們顯然能夠猜出你的問題,但在你發佈的內容中找不到。 –

回答

3

它看起來像你永遠不會創建onclickDic。你也永遠不會釋放它。

嘗試增加這些方法:

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle 
{ 
    self = [super initWithNibName:nibName bundle:nibBundle]; 
    if (self) 
    { 
     onclickDict = [[NSMutableDictionary alloc] init]; 
    } 
    return self; 
} 

- (void)dealloc 
{ 
    [onclickDict release]; 

    [super dealloc]; 
} 
2

它看起來不像onclickDic曾經分配過。確保在調用mapView:viewForAnnotation:方法之前分配實例。

此外,與問題無關,但您的toPush字典是不必要的。就在鍵/值增加onclickDic直接:

[onclickDic setValue:latlngDic forKey:[NSString stringWithFormat:@"%i", i]]; 
2

你似乎沒有實例self.onclickDic任何地方。即使有@synthesize,這也不適合你。最好的地方可能是init

調用沒有失敗的原因是Objective C中可以調用nil對象的函數。例如,這在調用委託的方法時通常使用。

+0

謝謝,它現在適用於:onclickDic = [[NSMutableDictionary alloc] init];什麼是釋放對象的最佳方式/時刻?因爲它不能在我添加對象的方法中完成。 – Melvin