Obj-c add c-struct to dictionary

I find it difficult to add a C-struct to NSDictionary.
C-struct is MKCoordinateRegion on MapKit.h.

This ad

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

and ad CLLocationCoordinate2D

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

MKCoordinateSpan is the same.

Now I want to add MKCoordinateRegion to 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 row has an error.
error message "Sending" MKCoordinateRegion "to an incompatible type parameter" id ""

Thanks.

+6
source share
2 answers

You cannot put the structure directly into the dictionary, but you can use NSValue to wrap it in such a way that it can be added.

An 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"]; 
+9
source

Try converting your structure to NSData

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

All Articles