Home > database >  how to put default value in fetch request predicate in coredata ios?
how to put default value in fetch request predicate in coredata ios?

Time:09-16

im working in ios swift, here i have used core data to store values and written some function to find the data and return it.

public func insertdetails (id:String, data:String, createdAt:String){
 do{
  try self.userdetails.operation { (context, save) throws -> Void in
       let model : User = try! context.create()
       model.id = id
       model.details = data
       model.createdat = createdAt
       save()
   }
  }
}
public func fetchdetails (Id:String) -> String{
do {
        let predicate: NSPredicate = NSPredicate(format: "id == %@", Id)
        let record: User = try! self.userdetails.fetch(FetchRequest<User>().filtered(with: predicate)).first ?? "" // **here im getting error**
        return record.details ?? ""
   }
}

in 1st code it represent object model. In 2nd code im facing error. im getting error as connot convert value of type string to expected argument type User, even if i forcewrap it , suppose value is not present, app gets crash. how to provide the default value in fetch operation.

CodePudding user response:

Your fetch request will return an array of User objects but you have a string on the right hand side of then nil coalescing operator; that is why you have an error.

You can't use a string as a replacement for a User. You probably don't want a nil coalescing operator here. Just handle the optional.

It is probably nicer if the function itself returns an optional string. Swift optionals are intended to replace sentinel values, such as the empty string you are using here.

public func fetchDetails (id:String) -> String? {
    let fetchRequest : FetchRequest<User> = User.fetchRequest()
    fetchRequest.predicate = NSPredicate(format: "id == %@", id)
    do {
        if let record = try self.userdetails.fetch(FetchRequest<User>().first {
            return record.details
        }
    } catch {
        print("fetch error - \(error)")
    }
    return nil
}

CodePudding user response:

The error occurs because first returns a User which is not related to an empty string.

And attach the predicate to the fetch request. Core Data filters the records on your behalf.

public func fetchdetails (Id:String) -> String{
    do {
            let fetchRequest : FetchRequest<User> = User.fetchRequest()
            fetchRequest.predicate = NSPredicate(format: "id == %@", Id)
            return try self.userdetails.fetch(fetchRequest).first?.details ?? ""
       }
    } catch {
       print(error)
       return ""
    }
}
  • Related