Wajih
Wajih

Reputation: 4393

How to query coredata with IN sql clause?

I have a Device Object, which has many Types. In my app I need to query some devices with specific type or a group of types. So the main function I use:

func get_ByDeviceType(_ type: Device.deviceType) -> [Device]? {
    let deviceFetch: NSFetchRequest<Device> = Device.fetchRequest()
    deviceFetch.predicate = NSPredicate(format: "type == \(type.rawValue)")

    do {
        let device = try context.fetch(deviceFetch)
        return device
    } catch {
        return nil
    }
}

Now when I try to get a group of Devices I tried this:

func get_ByDeviceTypes(_ types: [Device.deviceType]) -> [Device]? {
    var typesStr = ""
    var sep = ""
    for type in types {
        typesStr += sep + "\(type.rawValue)"
        sep = ","
    }
    let deviceFetch: NSFetchRequest<Device> = Device.fetchRequest()
    deviceFetch.predicate = NSPredicate(format: "type in (%@)", typesStr)

    do {
        let device = try context.fetch(deviceFetch)
        return device
    } catch {
        return nil
    }
}

But unfortunately it didn't work,

Is there a specific way to deal with this case. Thanks

Upvotes: 0

Views: 882

Answers (1)

shallowThought
shallowThought

Reputation: 19602

Assuming the type field of entity Device is of type String, use an Array of strings:

var typesStrings = [String]()
for type in types {
    typesStrings.append(type.rawValue)
} 
...
deviceFetch.predicate = NSPredicate(format: "type in (%@)", typesStr)

If it is of type Types. simple take the given array right away:

deviceFetch.predicate = NSPredicate(format: "type in (%@)", types)

Upvotes: 2

Related Questions