This is another function I think could be relevant. The function where I create the groups works fine and I can do topic.group after using it. It's after using another function when I can't do topic.group anymore. Function:
guard let filepath = Bundle.main.path(forResource: data_file, ofType: "csv") else {
return
}
var data = ""
do {
data = try String(contentsOfFile: filepath)
} catch {
return
}
var rows = data.components(separatedBy: "\n")
rows.remove(at: 0)
let dataController = DataController()
let context = dataController.container.viewContext
let topic = TopicData.getTopicFromName(name: topic_name, context: context)
for row in rows {
let columns = row.components(separatedBy: ",")
let name = columns[0]
let translation = columns[1]
let group_index = (columns[2] as NSString).integerValue
let previous_guessed: Bool = false
let character: Character = "?"
let group = GroupData.getGroupFromIndexAndTopic(index: Int16(group_index), topic: topic, context: context)
var already_shown: Bool = false
if translation.contains(character) {
already_shown = true
}
let word = Word(context: context)
word.namew = name
word.translation = translation
word.previous_guessed = previous_guessed
//word.group = group
group.addToWord(word)
word.already_shown = already_shown
do {
try context.save()
}
catch {
print("Context not saved")
}
}
}
And the function that gets Group:
static func getGroupFromIndexAndTopic(index: Int16, topic: TopicData, context:NSManagedObjectContext) -> GroupData {
let fetchRequest = NSFetchRequest<GroupData>(entityName: "GroupData")
fetchRequest.predicate = NSPredicate(format: "index_group = %d AND topic = %@", index, topic)
let groups = (try? context.fetch(fetchRequest)) ?? []
let group = groups.first!
return group
}