Rachel
Rachel

Reputation: 117

How to use NSPredicate to filter an array stored in CoreData?

I have a 'tags' array stored in CoreData (type 'Transformable') as an Array. I am making a request to CoreData to retrieve tags based on a searchText (string) input.

How can I use NSPredicate to filter the tags array based on the searchText?

let request = NSFetchRequest<NSFetchRequestResult>(entityName: Constants.Trip)

if(searchText != nil && searchText != "") {
    request.predicate = NSPredicate(format: "ANY %@ in tags", searchText!)
}

request.returnsObjectsAsFaults = false

Upvotes: 3

Views: 1077

Answers (2)

M Abubaker Majeed
M Abubaker Majeed

Reputation: 1003

You need to write predicate and set as a part of request like this ...

func getEntitiesWithName(_ entityName:String, sortKey:String?, predicate: NSPredicate?, ascending:Bool, context:NSManagedObjectContext) -> [NSManagedObject] {

    var results:[NSManagedObject] = [NSManagedObject]()

    context.performAndWait { () -> Void in

        let request = NSFetchRequest<NSFetchRequestResult>()
        request.entity = NSEntityDescription.entity(forEntityName: entityName, in: context)

        if let fetchPredicate = predicate {
            request.predicate = fetchPredicate
        }

        if let key = sortKey {

            let sortDescriptor = NSSortDescriptor(key: key, ascending: ascending, selector: #selector(NSString.localizedCaseInsensitiveCompare(_:)))
            request.sortDescriptors = [sortDescriptor];
        }

        results = (try! context.fetch(request)) as! [NSManagedObject]
    }

    return results
}

And you can set predicate like this

let predicate = NSPredicate(format: "isActive == %@", NSNumber(value: true as Bool))

Upvotes: 0

You cannot do that. Check this answer core data array of string filter

You might consider to have an entity for tags, or join the array of tags and have it as a whole string in your current entity, thus having the tags property as type String. For the last approach, you could search with the predicate below.

 NSPredicate(format: "tags CONTAINS[cd] %@", searchText)

The [cd] expression is to specify case and diacritic insensitivity respectively. You can get know more about the Core Data operations here.

I got some basic operators from the documentation and put them below:

BEGINSWITH The left-hand expression begins with the right-hand expression.

CONTAINS The left-hand expression contains the right-hand expression.

ENDSWITH The left-hand expression ends with the right-hand expression.

LIKE The left hand expression equals the right-hand expression: ? and * are allowed as wildcard characters, where ? matches 1 character and * matches 0 or more characters.

Upvotes: 2

Related Questions