2 garaster garaster 于 2013.01.04 10:48 提问

Objective-C添加c到dictionary中

添加C-结构到NSDictionary报错

C-struct是在MapKit.hMKCoordinateRegion

声明:

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

CLLocationCoordinate2D的声明:

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

MKCoordinateSpan和它一样

在添加MKCoordinateRegionNSDictionary中:

   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"];

第五行报错:Sending 'MKCoordinateRegion' to parameter of incompatible type 'id'

请高手指教

2个回答

love_loveec
love_loveec   2013.01.04 11:32
已采纳

不能直接添到dictionary,但是可以用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"];
vikeyToy
vikeyToy   2013.01.04 13:37

把结构转为NSData

NSData *data = [NSData dataWithBytes:&region length:sizeof(MKCoordinateRegion)];
 [param setObject:data forKey:@"region"];
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!