0

Hi I was succeeded in fetching data from coreData by using the below code.

class func fetchObject() -> [User]?{
    let context = getContext()
    var user: [User]? = nil
    do{
        user = try context.fetch(User.fetchRequest())
        return user
    }catch{
        return user
    }
}

Now I want to fetch a data in particular range.

For example I was saving some records with age as one column in that. Now I want to get the only 10 to 20 age persons from that coreData table. How can I achieve that. Please some one help me.Because I am new to ios.

Jonas Deichelmann
  • 3,513
  • 1
  • 30
  • 45
  • pass NSEntityDescrition to fetchrequest for any query e.g. https://useyourloaf.com/blog/core-data-queries-using-expressions/ – Gagan_iOS Mar 26 '18 at 06:01
  • Please use predicate after in fetch request you use. refer this https://stackoverflow.com/a/41641947/1142743 for more details – Vinodh Mar 26 '18 at 06:02

1 Answers1

1

You need to use predicate to filter out data.

    let fetchRequest : NSFetchRequest<User> = User.fetchRequest()
    fetchRequest.predicate = NSPredicate.init(format: "<AgeKey> <= %d && <AgeKey> >= %d", 10,20)
    user = try context.fetch(fetchRequest)
Priya
  • 735
  • 5
  • 10