2013-01-03 88 views
6

我無法將C-struct添加到NSDictionary。
C-struct是MapKit.h上的MKCoordinateRegion。obj-c將c-struct添加到字典

這聲明是

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

見沒有公認的答案[這裏](http://stackoverflow.com/questions/6538726/how-to-return-multiple-values-from-a-method/6539044 #6539044)。這個例子適用於數組,但字典仍然適用。 – Joe

回答

9

你不能直接把一個結構轉換成字典,但你可以使用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"]; 
+0

感謝您的回覆! –

+1

+1爲靈活/通用但優雅的解決方案。然而喬從他的評論中得出的相關答案構成了一個相關的具體解決方案 – Till

3

試試你的結構轉換爲NSData

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

非常感謝你! –

+0

不客氣! –