How to sort Core Data fetched properties

前端 未结 8 2067
太阳男子
太阳男子 2020-12-12 15:30

The Core Data Documentation states that:

The fetch request associated with the [fetched] property can have a sort ordering, and thus the fetched prope

8条回答
  •  情深已故
    2020-12-12 15:43

    For a single fetched property, Swift 4, Xcode 9.4:

    // retrieve the fetched property's fetch request    
    let fetchedPropertyRequest = (modelName.entitiesByName["entityName"]!.propertiesByName["fetchedPropertyName"] as! NSFetchedPropertyDescription).fetchRequest
    
    // set up the sort descriptors
    let sortDescriptors = [NSSortDescriptor(key: "keyName", ascending: true)]
    
    // add the sort descriptors to the fetch request
    fetchedPropertyRequest!.sortDescriptors = sortDescriptors
    

    Here's the same thing the loooonnnnnnggggggg way:

    // retrieve the fetched property's fetch request
    let theEntityDescription: NSEntityDescription = modelName.entitiesByName["entityName"]!
    let theFetchedPropertyDescription = theEntityDescription.propertiesByName["fetchedPropertyName"]! as! NSFetchedPropertyDescription
    let theFetchedPropertyRequest = theFetchedPropertyDescription.fetchRequest
    
    // set up the sort descriptors
    let sortDescriptor1 = NSSortDescriptor(key: "keyName", ascending: true)
    let theSortDescriptors = [sortDescriptor1]
    
    // add the sort descriptors to the fetch request
    theFetchedPropertyRequest!.sortDescriptors = theSortDescriptors
    

    Note: for this example, I force-unwrapped values. Make sure that you account for optional values in your actual code!

提交回复
热议问题