我只使用-setPropertiesToFetch获取实体的一些属性和一对一关系,并将结果类型设置为NSDictionaryResultType。 现在我在访问返回的关系的属性时遇到问题。只要我想访问一个属性,我就会得到一个NSInvalidArgumentException',原因是:无法识别的选择器被发送到实例
以下是完整的例外:
2011-03-23 11:02:10.435 ThurboApp[32996:207] -[_NSObjectID_48_0 lon]: unrecognized selector sent to instance 0x5a3f490
2011-03-23 11:02:10.441 ThurboApp[32996:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_NSObjectID_48_0 lon]: unrecognized selector sent to instance 0x5a3f490'
以下是相应的源代码:
- (void)fetchAllPois
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"POI" inManagedObjectContext:self.managedObjectContext];
request.entity = entity;
[request setResultType:NSDictionaryResultType];
[request setPropertiesToFetch:[NSArray arrayWithObjects:@"poiId",@"categoryId",@"poiTitle",@"coordinates", nil]];
request.sortDescriptors = nil;
request.predicate = nil;
NSError *error = nil;
self.fetchResult = [self.managedObjectContext executeFetchRequest:request error:&error];
}
- (MapPoint *)createMapPointFromDictionary:(NSDictionary *)dict
{
NSString *poiId = [dict objectForKey:@"poiId"];
NSString *title = [dict objectForKey:@"poiTitle"];
Coordinates *coords = (Coordinates *)[dict objectForKey:@"coordinates"];
NSNumber *category = [dict objectForKey:@"categoryId"];
CLLocationCoordinate2D coordinates = CLLocationCoordinate2DMake([coords.lat doubleValue], [coords.lon doubleValue]); //here raises the exception
MapPoint *p = [[[MapPoint alloc] initWithPoiId:poiId title:title category:[category intValue] coordinates:coordinates] autorelease];
return p;
}
坐标界面:
@interface Coordinates : NSManagedObject
{
}
@property (nonatomic, retain) NSNumber * lat;
@property (nonatomic, retain) NSNumber * alt;
@property (nonatomic, retain) NSNumber * lon;
@property (nonatomic, retain) NSManagedObject * poi;
@end
我已经检查过,字典中返回的值是正确的。偶数坐标指向一个Coordinate对象。
非常感谢帮助。
答案 0 :(得分:4)
好的,我设法解决了这个问题。你得到的关系是一个NSManagedObjectID,你可以使用objectWithID获取实体本身。 这是更新的代码:
- (MapPoint *)createMapPointFromDictionary:(NSDictionary *)dict
{
NSString *poiId = [dict objectForKey:@"poiId"];
NSString *title = [dict objectForKey:@"poiTitle"];
NSManagedObjectID *coordsID = (NSManagedObjectID *)[dict objectForKey:@"coordinates"]; //get the objectid
NSNumber *category = [dict objectForKey:@"categoryId"];
Coordinates *coords = (Coordinates *)[self.managedObjectContext objectWithID:coordsID]; //get the actual managedobject
CLLocationCoordinate2D coordinates = CLLocationCoordinate2DMake([coords.lat doubleValue], [coords.lon doubleValue]);
MapPoint *p = [[[MapPoint alloc] initWithPoiId:poiId title:title category:category coordinates:coordinates] autorelease];
return p;
}