Reputation: 10818
I have a core data object called Item
, it has 2 properties identifier
and type
Item
----
identifier
type (A/B)
It is possible to have 2 items with the same identifier but with different type.
I need to fetch all the items with one condition:
if two items has the same identifier, only show the A type.
In other words I want to make sure that the fetched items will have a unique identifier, and in the case of multiple items with the same identifier, priority will be given to item with type A.
I also prefer not to use NSDictionaryResultType
if possible
Upvotes: 1
Views: 145
Reputation: 46718
You can fetch from Core Data with a predicate to find (or count) objects with an identifier
(btw do NOT use id
, it is a reserved word in Cocoa) and you can sort by another property and then you can limit your fetch result to a single item.
That will give you your priority you are looking for. However, I strongly recommend against handling the issue that way and instead writing your creation code to avoid having duplicates in the first place.
What I am saying is that you can't "fetch all the items with one condition...". What you can do is fetch per item (using the identifier), limiting the fetch to a single result sorted by type
which will give you your results.
If you wanted all items of type "a", that is doable.
If you wanted all items and filtered on type in a second pass in memory, you could do that
You cannot combine them.
Now, if you want to fetch per item, filtering on the type it would look like this:
NSManagedObjectContext *moc = ...;
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"MyEntity"];
[fetchRequest setFetchLimit:1];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"identifier == %@", myIdentifier];
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"type" ascending:YES];
NSArray *sortArray = [NSArray arrayWithObject:sort];
[fetchRequest setSortDescriptors:sortArray];
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:fetchRequest error:&error];
if (!results) {
NSLog(@"Error: %@\n%@", [error localizedDescription], [error userInfo]);
abort();
}
id mySingleObject = [results lastObject];
NOTE: This code was written in the browser, there are probably errors.
Upvotes: 1