Eliza
Eliza

Reputation: 21

Retrieving data from coredata by it's date attribute

How can I find an item I added to the core data by it's date attribute? Here is the code I have so far. I am using a predicate to filter the request. I want to get the data to then eventually update the text stored in that particular entry

       
var request = NSFetchRequest<NSManagedObject>(entityName: "Object")
let predicate = NSPredicate(format: "dateOfObject == %i", datePicker.date as CVarArg)
request.predicate = predicate
request.fetchLimit = 1
        

do{
      let count = try context.count(for: request)
      print(count)

      if(count == 0){
                userText.text = ""
      }
      else{
            // A matched object is in the coredata
            let objectFetched = try! context.fetch(request)
            userText.text = (objectFetched[0]).objectText
               
          }
  }


I am adding to the coredata like this:

let newObject = Object(context: self.context)
newObject.dateOfObject = date

do{
        try self.context.save()
  } 
catch{
        print("not valid")
  }

I don't think this code is comparing the two dates properly in NSPredicate(format: "dateOfObject == %i", datePickerr.date as CVarArg)

I also get the error NSCFNumber timeIntervalSinceReferenceDate]: unrecognized selector sent to instance.... for the: context.count(for: request).

Upvotes: 1

Views: 216

Answers (1)

vadian
vadian

Reputation: 285069

Dateis treated as object, the object specifier is %@

let predicate = NSPredicate(format: "dateOfObject == %@", datePicker.date as CVarArg)

Your code can be shortened

let request = NSFetchRequest<Object>(entityName: "Object")
// or even more recommended 
// let request : NSFetchRequest<Object> = Object.fetchRequest()
request.predicate = NSPredicate(format: "dateOfObject == %@", datePicker.date as CVarArg)
request.fetchLimit = 1
        
do {        
     if let object = try context.fetch(request).first {
        userText.text = object.objectText   
     } else {
        userText.text = ""
     }
} catch { print(error) }

and please delete the redundant object prefixes and suffixes in the attribute names (text and date is sufficient). The entity clearly indicates that it's an Object

Upvotes: 1

Related Questions