Can't pass Date to NSPredicate(format: ...) without as CVarArg
The %@
format expect a Foundation object as argument, compare
"Predicate Format String Syntax" in the "Predicate Programming Guide".
Therefore you have to cast the overlay type Date
back to its Foundation
counterpart NSDate
:
let endDate = Date()
let pred = NSPredicate(format: "endDate == %@", endDate as NSDate)
How to use NSPredicate with Date type
To use the current date as a predicate parameter just create an NSDate
instance
let datePredicate = NSPredicate(format: "due_date < %@", NSDate())
For a date variable you can use
aDate as NSDate
or
aDate as CVarArg
If you get the error
'Date?' is not convertible to 'NSDate'
then the code is not the real code because both Date()
and NSDate()
are non-optional.
Unable to query for date using NSPredicate in Swift
NSPredicate(format:_:)
takes a format string and a list of arguments, but you're passing a simple string. This doesn't work, since this initializer doesn't just call stringWithFormat:
on the parameters, but actually looks at the arguments' type information as it's building the predicate.
You can use that initializer by passing the date as an argument:
let datePredicate = NSPredicate(format: "date > %@", currentDate)
Filter fetchRequest for year/month using NSPredicate
You cannot predicate like this, but you can create two Dates
from your month and year which start day of month and end day of month.
Now you need to simply predicate like this way.
let predicate = NSPredicate(format: "%K >= %@ && %K <= %@", "DateAttribute", startDateOfMonth as NSDate, "DateAttribute", endDateOfMonth as NSDate)
Edit: If you don't know how to create date for startDateOfMonth
and endDateOfMonth
, then you can create it using DateComponents
.
let selectedMonth = 11
let selectedYear = 2015
var components = DateComponents()
components.month = selectedMonth
components.year = selectedYear
let startDateOfMonth = Calendar.current.date(from: components)
//Now create endDateOfMonth using startDateOfMonth
components.year = 0
components.month = 1
components.day = -1
let endDateOfMonth = Calendar.current.date(byAdding: components, to: startDate!)
Swift coreData - format date and use it in predicate
Don't use a custom string format for that purpose. You want to fetch
all entries which are related to an Agendadate object with a date
on the same day as the given day.
So you compute the start and end of that day first:
let date = Date()
let cal = Calendar.current
let startOfDay = cal.startOfDay(for: date)
let endOfDay = cal.date(byAdding: .day, value: 1, to: startOfDay)!
Then use this SUBQUERY:
let predicate = NSPredicate(format: "SUBQUERY(agendaDates, $a, $a.dates >= %@ AND $a.dates < %@).@count > 0",
startOfDay as NSDate, endOfDay as NSDate)
It tests $a.dates >= startDate AND $a.dates < endDate
for all
related objects, and yields true if there is at least one matching
the condition.
Swift 5 NSFetchRequest predicate when trying to lookup a String UUID
You can replace your predicate with this:
guard let uuidQuery = UUID(uuidString: uuid) else { return [] } // no valid UUID with this code
request.predicate = NSPredicate(format: "%K == %@", #keyPath(ExistingUsers2.uuid), uuidQuery as CVarArg)
Everything else should work.
UPDATE
This is the code that finally worked, thanks for your help @André Henrique da Silva
func loadUser(uuid: String) -> [ExistingUsers2] {
let request : NSFetchRequest<ExistingUsers2> = ExistingUsers2.fetchRequest()
let uuidQuery = NSUUID(uuidString: uuid)
request.predicate = NSPredicate(format: "uuid == %@", uuidQuery! as CVarArg)
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
do {
existingUsersArray = try context.fetch(request)
} catch {
print("Error fetching data from context \(error)")
}
return existingUsersArray
}
Core Data NSPredicate: Return all objects which are related to another object whos ID appears in a given array
Try adding an @count
to your subquery.
NSPredicate(format: "SUBQUERY(events, $event, ANY $event.clientID in %@).@count != 0", clientIDs as CVarArg)
Checkout these docs for bit of a reference. It is for NSExpression but the "Discussion" section has an example of a subquery.
Swift core data NSFetchRequest predicate to fetch date time
I was able to update uvIndexNowRequest to find my solution. See below code
static var uvIndexNowRequest: NSFetchRequest<UVHour>
{
let dateTimeNow = Date()
let formatter = DateFormatter()
formatter.timeZone = .current
formatter.dateFormat = "MMM/d/yyyy hh a"
// Find date String from 'formatter.dateFormat'
let dateHourStr = formatter.string(from: dateTimeNow)
// Get date from dateHourStr
let someDateTimeOpt = formatter.date(from: dateHourStr)
let request: NSFetchRequest = UVHour.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(key: "order", ascending: true)]
if let someDate = someDateTimeOpt {
request.predicate = NSPredicate(format: "date_time == %@", someDate as CVarArg)
}
return request
}
Related Topics
Swift Closures - Capturing Self as Weak
Sum Values of Properties Inside Array of Custom Objects Using Reduce
How to Bind a Variable to Multiple Alternatives in a Switch Statement
Swift Safe Area Layout Guide and Visual Format Language
How to Set Countdowntimer Mode in Datepicker on Swiftui
What Is the Usecase for Ignored Parameters in Swift
How to Create a Static Class in Swift
Hex String to Character in Pure Swift
How to Make Protocol Associated Type Require Protocol Inheritance and Not Protocol Adoption
How to Open File Dialog with Swiftui on Platform "Uikit for MAC"
Add Custom Header to Collection View Swift
Include an Extension for a Class Only If iOS11 Is Available
Swift: How to Change a Property's Value Without Calling Its Didset Function
Enum with Identical Cases Names with Associated Values of Different Types
How to Get Next Case of Enum(I.E. Write a Circulating Method) in Swift 4.2