CoreData conditionally fetching on NSDate using NSPredicate (swift)
I guess you are sending parameters to the predicate in NSDate format :
let predicate = NSPredicate(format: "time>= \(startTime) AND time<= \(endTime)")
Here your startTime and endTime is of type NSDate . Try to convert it in String format and pass it to the predicate . It should work .
Reference : NSPredicate: filtering objects by day of NSDate property
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)
How fetch objects with NSDate of today using NSPredicate?
What I do is compare it to the start and end of the day and have a couple helper functions to calculate them:
class DateHelper{
internal class func startOfDay(day: NSDate) -> NSDate {
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let unitFlags: NSCalendarUnit = [.Minute, .Hour, .Day, .Month, .Year]
let todayComponents = gregorian!.components(unitFlags, fromDate: day)
todayComponents.hour = 0
todayComponents.minute = 0
return (gregorian?.dateFromComponents(todayComponents))!
}
internal class func endOfDay(day: NSDate) -> NSDate {
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let unitFlags: NSCalendarUnit = [.Minute, .Hour, .Day, .Month, .Year]
let todayComponents = gregorian!.components(unitFlags, fromDate: day)
todayComponents.hour = 23
todayComponents.minute = 59
return (gregorian?.dateFromComponents(todayComponents))!
}
}
So in your code, you would call:
request.predicate = NSPredicate(format: "(dateStart => %@) AND (dateStart <= %@)", DateHelper.startOfDay(today), DateHelper.endOfDay(today))
Display results from CoreData using NSPredicate in Swift
The predicate needs to be added to the fetch request, for example:
let request = NSFetchRequest(entityName: "Your entity name")
let predicate = NSPredicate(format: "A == %d", 1)
request.predicate = predicate
fetchedResultsController = NSFetchedResultsController(
fetchRequest: request,
managedObjectContext: managedObjectContext!,
sectionNameKeyPath: nil,
cacheName: nil)
What goes to the predicate depends on your goals. In a next step you will need to update the fetch request and reload the data as you change the selected item in the segmented control. In your IBAction
that is called when the segmented control changes, get sender.selectedSegmentIndex
and create the new predicate based on the index.
The code to refetch will look something like this:
Swift 2
fetchedResultsController.fetchRequest.predicate = NSPredicate(format: "A = %d", some_int_goes_here)
do {
try fetchedResultsController.performFetch()
}
catch let error as NSError {
NSLog("%@", error.localizedDescription)
}
catch {
fatalError()
}
tableView.reloadData()
If you do Swift 1.2, omit the error handling, of course, something like this:
fetchedResultsController.fetchRequest.predicate = NSPredicate(format: "A = %d", some_int_goes_here)
fetchedResultsController.performFetch()
tableView.reloadData()
Check Core Data for an entry with Today's Date & perform function
You need to use a date range from start of day to end of day (midnight to midnight) in a compound predicate. Here is a solution based on a similar SO question
var calendar = Calendar.current
calendar.timeZone = NSTimeZone.local
let dateFrom = calendar.startOfDay(for: Date())
let dateTo = calendar.date(byAdding: .day, value: 1, to: dateFrom)
let fromPredicate = NSPredicate(format: "timestamp >= %@", dateFrom as NSDate)
let toPredicate = NSPredicate(format: "timestamp < %@", dateTo! as NSDate)
let waterPredicate = NSPredicate(format: "drinkWater = %@", "1")
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Drink")
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [waterPredicate, fromPredicate, toPredicate])
NSPredicate: filtering objects by day of NSDate property
Given a NSDate * startDate and endDate and a NSManagedObjectContext * moc:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@)", startDate, endDate];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:moc]];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];
URI typed attributes in CoreData: how to query with NSPredicate
I'm answering to not let that question without an answer, but in my opinion, we three @nylki (the author), @Joakim Danielson and myself answered it together. I'll mark it as "Community Wiki" then.
URI
in CoreData is a for URL
objects. It's written as such in the documentation of NSAttributeDescription.AttributeType
for the NSAttributeDescription.AttributeType.uri
.
LIKE
keyword in the predicate is for String comparison as stated by the Predicate Format String Syntax documentation, so we need to use =
instead.
So the answer is:
NSPredicate(format: "imageUrl = %@", imageUrl as CVarArg)
Or
NSPredicate(format: "imageUrl = %@", argumentArray: [imageUrl])
if we don't want to use the as CVarArg
.
A better way to avoid typo would be to use %K
placeholder which is for %K is a var arg substitution for a key path.
. Combined to #keyPath()
:
NSPredicate(format: "%K = %@", argumentArray: [#keyPath(YourEntityClass.imageUrl), imageUrl])
That way, if we wrote by error "imageUrI = %@"
with an uppercase i
instead of l
that with might not see, we ensure the path.
Can I use an NSPredicate in Swift with a nil argument?
It looks as if it is (with the current Xcode 6 beta 3 release) generally difficult
to pass nil
in a variable argument list.
This seems to work:
let predicate = NSPredicate(format: "parentFolder == %@", 0)
print(predicate)
// Output: parentFolder == nil
But the easiest solution would be to simply write the predicate as
NSPredicate(format: "parentFolder == nil")
How to retrieve CoreData that satisfies a condition swift 2
You need to add a NSPredicate to your fetchRequest.
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSPredicate_Class/
fetchRequest.predicate = NSPredicate(format: "flag == %@", "3")
Related Topics
Clipping Sound with Opus on Android, Sent from iOS
Wkwebview Decidepolicyfornavigationaction Being Call After the Long Press Recogniser Ended
How to Add the Same Background Image to All Views in My iOS App Using Swift
Dynamic Uitablecellview Height
Collectionview Flowlayout Overlapping When Scrolling Not Working
Indexing into Array of Functions: Expression Resolves to an Unused L-Value
Swift3: Live Uilabel Update on User Input
iPhone Simulator Plays Video, Real Device Won'T
Scroll All the Way Down to the Bottom of Uitableview
Updating the Status Bar Style Between View Controllers
Delegates: Pass Data Without Segue
Swift 3:Url Image Makes Uitableview Scroll Slow Issue
iOS Pass Data Back from Viewcontroller2 to Viewcontroller 1 with Presentmodalsegue
Ios: How to Create Expandable Tableview in Swift Without Using Third Party Libraries or Pods