2011-08-18 122 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