Ios 根据获取的属性对实体进行排序

Ios 根据获取的属性对实体进行排序,ios,swift,core-data,Ios,Swift,Core Data,在我的应用程序(用Swift编写)中,我使用了一个核心数据模型,其中有两种配置,每种配置使用不同的保存路径(一种在应用程序包中是只读的,另一种在Documents文件夹中)。我在两种配置之一中设置了具有以下属性的实体“Domanda”: 在另一个配置中,我设置了一个具有以下属性的实体“StatDomanda”: “StatDomanda”用于用户数据,而“Domanda”用作预加载源。我知道我不能在两个实体(两种配置)之间建立关系,但我会根据“StatDomanda”实体的“correte”属性

在我的应用程序(用Swift编写)中,我使用了一个核心数据模型,其中有两种配置,每种配置使用不同的保存路径(一种在应用程序包中是只读的,另一种在Documents文件夹中)。我在两种配置之一中设置了具有以下属性的实体“Domanda”: 在另一个配置中,我设置了一个具有以下属性的实体“StatDomanda”: “StatDomanda”用于用户数据,而“Domanda”用作预加载源。我知道我不能在两个实体(两种配置)之间建立关系,但我会根据“StatDomanda”实体的“correte”属性对“Domanda”实体进行排序,其中StatDomanda.numero==Domanda.numero,StatDomanda.argomento==Domanda.argomento.nomergomento。 并非所有的“Domanda”对象都有相应的“StatDomanda”对象。 我用这个谓词在“Domanda”实体中设置了一个获取的属性(称为“statistiche”)

$FETCH_SOURCE.numero=numero和 $FETCH_SOURCE.argomento.nomeArgomento=argomento

但我不知道如何使用它来排列对象


谢谢你的帮助

我找到了一个解决方案,我不知道这是否是最好的方法,但它确实有效! 在我的核心数据管理器类(ModelManager)中,我使用此函数获取所有“Domanda”实体:

func getAllQuestions() -> [Domanda] {
        let fetchRequest = NSFetchRequest(entityName: "Domanda")
        let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [Domanda]
        return fetchResults!
    }
在我的ViewController中,我使用以下代码根据“statistiche”获取属性的属性“corrette”获取“Domanda”实体的排序数组:

override func viewDidLoad() {
    super.viewDidLoad()

    var arrayDomande  = ModelManager.instance.getAllQuestions()
    var sortedArrayDomande = self.sortArray(arrayToSort: arrayDomande)
}

func sortArray(arrayToSort sarray: Array<Domanda>) -> Array<Domanda> {

        // 1 - Filter the array to find only questions that have stats
        var onlyAnswered = sarray.filter({($0.valueForKey("statistiche") as [Domanda]).count == 1})

        // 2 - Sort the array based on fetched property
        var sortedArrayDomande = sorted(onlyAnswered, {
            let first = ($0.valueForKey("statistiche") as [StatDomanda])[0]
            let firstC = first.corrette.integerValue

            let second = ($1.valueForKey("statistiche") as [StatDomanda])[0]
            let secondC = second.corrette.integerValue

            return firstC > secondC
        })

        return sortedArrayDomande
    }
再见,伙计们,下次见

// 2 - Sort the array based on fetched property
var sortedArrayDomande = sorted(onlyAnswered, {($0.valueForKey("statistiche") as [StatDomanda])[0].corrette.integerValue > ($1.valueForKey("statistiche") as [StatDomanda])[0].corrette.integerValue})