Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

obj-c add c-struct to dictionary

I have trouble to add C-struct to NSDictionary.
The C-struct is MKCoordinateRegion on MapKit.h.

That declaration is

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

and CLLocationCoordinate2D's declaration is

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

MKCoordinateSpan is same.

Now, I want add the 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 line has error.
error message is "Sending 'MKCoordinateRegion' to parameter of incompatible type 'id'"

Thanks.

like image 830
Conao3 Avatar asked Jan 03 '13 14:01

Conao3


2 Answers

You can't put a struct directly into a dictionary, but you can use an NSValue to wrap it in such a way that it can be added.

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"];
like image 117
Stephen Darlington Avatar answered Oct 01 '22 10:10

Stephen Darlington


Try converting your struct to NSData

NSData *data = [NSData dataWithBytes:&region length:sizeof(MKCoordinateRegion)];
 [param setObject:data forKey:@"region"];
like image 20
Andrey Chernukha Avatar answered Oct 01 '22 10:10

Andrey Chernukha