I'm trying to use a value from a UITextField
by passing it to a function which takes it as an argument and uses it as a NSPredicate
. However, I'm getting zero results returned even though I've verified that the record I want is in the Core Data store.
The value is coming from this UITextField:
@IBOutlet weak var liftName: UITextField!
and I'm calling the function to retrieve the record like so:
let lift = fetchLift(liftName.description)
and here's the function:
func fetchLift(liftNameFilter: String? = nil) -> Lift {
let fetchRequest = NSFetchRequest(entityName: "Lift")
if let liftNameFilter = liftNameFilter {
let filterPredicate = NSPredicate(format: "liftName = [c] %@", liftNameFilter)
fetchRequest.predicate = filterPredicate
}
do {
if let results = try coreDataStack.managedObjectContext.executeFetchRequest(fetchRequest) as? [Lift] {
lift = results
}
} catch {
fatalError("There was an error fetching the lifts")
}
return lift![0]
}
I've tried things like:
commenting out the predicate:
// let filterPredicate = NSPredicate(format: "liftName = [c] %@", liftNameFilter) // fetchRequest.predicate = filterPredicate }
and I get all 11 records in that entity returned so now I know it has to do with the predicate.
I also hard coded one of the values to search for like so:
let filterPredicate = NSPredicate(format: "liftName = [c] %@", "Bench Press")
and retrieved the record I need.
I did some caveman debugging and determined that this is what's being passed to the function:
<UITextField: 0x7ffb8340f0e0; frame = (86.5 148; 272.5 30); text = 'Bench Press'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x7ffb81cf03e0>; layer = <CALayer: 0x7ffb8340e320>>
so I'd expect that text
value to be plucked right out of there and used as the predicate but it's not.
I feel like this is one of those obvious things that I'm blind to now that I've stared at it so long. Hoping someone can help me out. Thanks.
You should use the text
property of the UITextField
to get the inputed value rather than using description
.
let lift = fetchLift(liftName.text)
And just change your predicate to below:
let filterPredicate = NSPredicate(format: "ANY liftName CONTAINS[c] %@", liftNameFilter)