obj-c将c-struct添加到字典中

时间:2013-01-03 14:06:55

标签: iphone objective-c dictionary struct mapkit

我很难将C-struct添加到NSDictionary中 C-struct是MapKit.h上的MKCoordinateRegion。

该声明是

typedef struct {
    CLLocationCoordinate2D center;
    MKCoordinateSpan span;
} MKCoordinateRegion;

和CLLocationCoordinate2D的声明是

typedef struct {
    CLLocationDegrees latitude;
    CLLocationDegrees longitude;
} CLLocationCoordinate2D;

MKCoordinateSpan是一样的。

现在,我想将MKCoordinateRegion添加到NSDictionary。

    CLLocationCoordinate2D center = CLLocationCoordinate2DMake(40.723128, -74.000694);
    MKCoordinateSpan span = MKCoordinateSpanMake(1.0, 1.0);
    MKCoordinateRegion region = MKCoordinateRegionMake(center, span);
    NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
    [param setObject:region forKey:@"region"];

5行有错误。
错误消息是“将'MKCoordinateRegion'发送到不兼容类型'id'的参数”

感谢。

2 个答案:

答案 0 :(得分:11)

您不能将结构直接放入字典中,但是可以使用NSValue将其包装起来以便可以添加它。

Example

typedef struct { 
  float real; 
  float imaginary; 
} ImaginaryNumber; 

ImaginaryNumber miNumber; 
miNumber.real = 1.1; 
miNumber.imaginary = 1.41; 

NSValue *miValue = [NSValue value: &miNumber 
                        withObjCType:@encode(ImaginaryNumber)]; 

[param setObject:miValue forKey:@"region"];

答案 1 :(得分:3)

尝试将结构转换为NSData

NSData *data = [NSData dataWithBytes:&region length:sizeof(MKCoordinateRegion)];
 [param setObject:data forKey:@"region"];