iPhone CoreData funky fetch-request: I want to build function to retrieve array of Unique-CategoryCodes for my products I have Entity "Product" and there is a field(Property) Category. Of course Category is the Relationship to the Categories Entity.
This if my function:
- (NSArray *)uniqueCategoriesWithQuery:(NSString *)query {
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Product" inManagedObjectContext:[self managedObjectContext]];
NSDictionary *entityProperties = [entity propertiesByName];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
[request setReturnsDistinctResults:YES];
[request setPropertiesToFetch:[NSArray arrayWithObject:[entityProperties objectForKey:@"Code"]]];
[request setResultType:NSDictionaryResultType];
[request setIncludesSubentities:YES];
[request setIncludesPropertyValues:YES];
NSError *fetchError = nil;
NSArray *result = [[self managedObjectContext] executeFetchRequest:request error:&fetchError];
DebugLog(@"%@", result);
if (fetchError == nil && [result count] > 0) {
return result;
}
return nil;
}
MyResult: 2010-12-10 05:55:33.683 iApp[3453:307] -[ShoppingHelper uniqueCategoriesWithQuery:] [Line 1193] ( { Category = "0x495a200 "; }, { Category = "0x4959ce0 "; } )
Code works well but I can not use results at all. I have got my categories ... but ID' instead of NSStrings.. How to consume it?
mayb开发者_StackOverflow中文版e I should be using: [request setPropertiesToFetch:[NSArray arrayWithObject:[entityProperties objectForKey:@"Categories.Code"]]];
to get the NSStrings in the Distinct NSDictionary?
OR
find Category BY ID - How to do it?
If you avoid using NSDictionaryResultType
, and instead let it return managed objects, you can just access the Category
objects through the appropriate property on the returned Product
objects. From there, you can get whatever information you need from each category. Although, if you do this, and have a very large result set, you may want to set the fetch batch size.
精彩评论