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

Con*_*ao3 8 iphone struct dictionary objective-c mapkit

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

那个宣言是

typedef struct {
    CLLocationCoordinate2D center;
    MKCoordinateSpan span;
} MKCoordinateRegion;
Run Code Online (Sandbox Code Playgroud)

和CLLocationCoordinate2D的声明是

typedef struct {
    CLLocationDegrees latitude;
    CLLocationDegrees longitude;
} CLLocationCoordinate2D;
Run Code Online (Sandbox Code Playgroud)

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"];
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

Ste*_*ton 11

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

示例:

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"];
Run Code Online (Sandbox Code Playgroud)