Search code examples
swiftcore-datansfetchrequest

generate fetch request across two entities with NO relationship in Swift


I currently have a checklist application with two separate entities. The first contains all the necessary item information (name, group, set, year, etc) and the second contains all the user editable information (owned, wanted, etc). They both share a uniqueID attribute as well. I've set it up this way (with no relationship) because I am trying sync with iCloud and the checklist information is way to large to sync, so this way I only need to sync the user editable information (much less data). That is all working swimmingly. The one hiccup I'm having is as follows:

I want to be able to filter the table view generated from the item information by the owned (or wanted) data in the user editable information. Essentially, I would need to be able to execute a fetch request on the user editable information to fetch all owned items, then use the resulting array and fetch items from the item entity that have the matching uniqueID. Is it possible to execute a fetchrequest to match all items in the array generated in the first fetchrequest (comparing the uniqueID)? Perhaps with some sort of for loop? Or, even better, some sort of aggregate fetch request?

Any tips would be appreciated!

-- Thanks! Editing to include code for answer:

I ended up using this code to create the array of "owned items" from one entity (UserEdits)

var uniqueIDs = [String]()

        if let ownedTemplate = CDHelper.shared.model.fetchRequestTemplateForName("AllOwnedItems"), let ownedRequest = ownedTemplate.copy() as? NSFetchRequest {
            do {
                if let ownedItems = try CDHelper.shared.context.executeFetchRequest(ownedRequest) as? [UserEdits] {
                    for ownedItem in ownedItems {
                        uniqueIDs.append(ownedItem.uniqueID!)
                    }
                }
            } catch {print("ERROR executing a fetch request: \(error)")}
        }

And then passed that array into the fetch request against the larger entity (item)

if let template = CDHelper.shared.model.fetchRequestFromTemplateWithName("FilteredMainListOwned", substitutionVariables: ["SORT1" : lineFilter.lowercaseString, "SORT2" : uniqueIDs]) {
            let request = template as NSFetchRequest
            self.filter = request.predicate
            self.reloadFRC(request.predicate)
        }

Where the substitution expressions are:

group BEGINSWITH $SORT1
uniqueID IN $SORT2

Solution

  • It sounds like you're looking for NSPredicate's IN aggregate operation. If you have a known set of identifiers you want to load you could write an expression something like:

    let ids = ["1", "2"]
    NSPredicate("%K IN %@", "uniqueID", ids)