问题
A->>B
I have two entities A&B and each are related as one to many relationship. I am trying to access specific B attribute value and all A entity attributes by grouping. However I am getting error as [_NSObjectID_48_1 userName]: unrecognized selector sent to instance when I try to access relationship object of B(that is a).
NSManagedObjectContext *context = [[SamCoreDataHelper sharedInstance] managedObjectContext];
NSFetchRequest *fr = [[NSFetchRequest alloc] initWithEntityName:@"B"];
NSError *error;
NSExpressionDescription *total = [[NSExpressionDescription alloc] init];
[total setExpression:[NSExpression expressionWithFormat:@"@sum.marks"]];
[total setName:@"total"];
[total setExpressionResultType:NSDecimalAttributeType];
[fr setPropertiesToFetch:[NSArray arrayWithObjects:@"subject",@"a", total, nil]];
[fr setPropertiesToGroupBy:[NSArray arrayWithObjects:@"subject", @"a", nil]];
[fr setRelationshipKeyPathsForPrefetching:[NSArray arrayWithObject:@"a"]];
fr.returnsObjectsAsFaults = NO;
[fr setResultType:NSDictionaryResultType ];
NSArray *resultArray = [context executeFetchRequest:fr error:&error];
for (NSDictionary *result in resultArray) {
NSNumber *total = [result valueForKey:@"total"];
NSString *subject = [result valueForKey:@"subject"];
A *a = [result objectForKey:@"a"];
NSLog(@"%@", a.useName);// Here I am getting error as **[_NSObjectID_48_1 userName]: unrecognized selector sent to instance**
}
回答1:
You will receive "object id" instead of instance of NSManagedObject for the relative object when the result of NSFetchRequest is set to NSDictionaryResultType.
So you need to fetch it "by object id":
A * a = (A*)[ managedObjectContext objectWithID:[result valueForKey:@"a"]];
NSLog("%@",a.userName );
UPD:
fr.returnsObjectsAsFaults = NO;
is useless here because the return type is NSDictionaryResultType.
回答2:
How about using the following for iteration..
for (A *a in resultArray) {
NSLog(@"%@", a.useName);
}
来源:https://stackoverflow.com/questions/29010721/core-data-getting-nsobjectid-48-1-username-unrecognized-selector-sent-to-ins