gpt4 book ai didi

swift - 试图填充 NSManagedObjects 数组的数组

转载 作者:行者123 更新时间:2023-11-28 11:39:19 25 4
gpt4 key购买 nike

我正在从 CoreData 模型中获取数据并且效果很好。我得到一组 NSManagedObjects (NSMO),每个都是一个具有其他一些属性的文档。

NSMO 的属性之一是日期,为了填充 TableView,我使用日期中的“年份”作为 TableView 中的部分。

要获得每年(部分)的 NSMO,我必须过滤数组。但是,如果我在“cellForRowAtIndexPath”中进行过滤,应用程序的效率会非常低。所以我考虑了一个解决方案:

在获取一个数组中的所有文档后,我可以过滤每年的数组并填充 NSMO 数组的数组。

var documentArray = [Document]()  // To fetch all the documents.
var documentArrayPerSection = [[Document]]() // To filter per section.

其中“文档”是 NSMO。

例如,对于第一部分,我们有数组:

documentArrayPerSection[0]

等等。

var documentArray = [Document]()
var documentArrayPerSection = [[Document]]()
let yearSections = ["2005","2006","2007","2008","2009","2010","2011","2012","2013"]

func fetchDocuments() {

// We make the request to the context to get the documents we want.

do {

documentArray = try context.fetchMOs(requestedEntity!, sortBy: requestedSortBy, predicate: requestedPredicate)

// Arrange the documentArray per year using the variable documentArrayPerSection.
for index in 0...yearSections.count - 1 {

documentArrayPerSection[index] = documentArray.filter({ (document) -> Bool in
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"
let yearSection = formatter.string(from: document.date!)
return yearSection == self.yearSections[index]
})

}

} catch {

print("Error fetching data from context \(error)")

}

}

应用程序崩溃时总是提示“索引超出范围”。而且我不知道如何解决这个问题,因为变量必须是全局的,才能从“cellForRowAtIndexPath”访问并且必须初始化为空白。

最佳答案

Swift 4+ 提供了一种非常简单方便的方法来对数组进行分组:Dictionary(grouping:by:)

let calendar = Calendar.current
let groupedDictionary = Dictionary(grouping: documentArray, by: {calendar.component(.year, from: $0.date)})

分别返回一个以年份为键(作为Int)的字典和一个Document数组作为值。

如果你想要字符串键,将闭包更改为

{ String(calendar.component(.year, from: $0.date)) }

然后您可以使用

获取您的节数组
let yearSections = groupedDictionary.keys.sorted()

并获取对应的数组

let yearArrays = yearSections.map{ groupedDictionary[$0]! }

不需要Dateformatter

关于swift - 试图填充 NSManagedObjects 数组的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54161637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com