UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: FetchLimit Core Data

Forums > SwiftUI

How can I limit numer of quotes in my fetch request, for example 100 quotes. I know it might use fetch limit liked request.fetchlimit = 100. However, I get the error NSFetchRequest cannot convert to FetchRequest. Any ideas how to get this one done?


extension Quote : Identifiable {
  @NSManaged var content : String
  @NSManaged var author : String?
  @NSManaged var category : String
  @NSManaged var isLiked : Bool

  static func basicFetchRequest() -> FetchRequest<Quote> {
    FetchRequest(entity: Quote.entity(), sortDescriptors: [])
  }
}

In Content View

  let fetchRequest = Quote.basicFetchRequest()
  var quotes : FetchedResults<Quote>  {
    fetchRequest.wrappedValue
  }

 ``

3      

You would use a different initializer for the FetchRequest, like so:

static func basicFetchRequest() -> FetchRequest<Quote> {
    let request = fetchRequest()
    request.fetchLimit = 100
    //set up any predicates or sort descriptors
    return FetchRequest(fetchRequest: request)
}

4      

it still give the errors

Cannot convert return expression of type 'FetchRequest<NSFetchRequestResult>' to return type 'FetchRequest<Quote>'

3      

Ah, right, that's because FetchRequest is only available in a SwiftUI View, since it uses the managedObjectContext property from the environment, which is only available in a View. So you need to construct an NSFetchRequest within your managed object subclass and pass it to the FetchRequest within your View.

In your managed object subclass:

static func fetchRequestLimit100() -> NSFetchRequest<Quote> {
    let request: NSFetchRequest<Quote> = Quote.fetchRequest()
    request.fetchLimit = 100
    //set up any predicates or sort descriptors
    return request
}

And then in your View:

@FetchRequest(fetchRequest: Quote.fetchRequestLimit100)
var quotes: FetchedResults<Quote>

5      

Thank you @roosterboy, it works perfectly

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.