向NSMutableDictionary添加条目

时间:2011-08-18 11:28:30

标签: objective-c ios nsdictionary 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

3 个答案:

答案 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];
}

答案 1 :(得分:2)

它看起来不像onclickDic。确保在调用mapView:viewForAnnotation:方法之前分配实例。

此外,与问题无关,但您的toPush字典是不必要的。只需将密钥/值直接添加到onclickDic

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

答案 2 :(得分:2)

您似乎无法在任何地方实例化self.onclickDic。即使使用@synthesize,也不会为您完成此操作。最好的地方可能是init

调用没有失败的原因是,在Objective C中调用nil对象上的函数是可以的。例如,在调用委托方法时通常会使用此方法。