I am writing a function in my database object that can read from the database.
I am storing vocab objects
@Model
final class Vocab: Codable{
var id: Int
var word: String
var meaning: String
var pronunciationUrl: String
var similar: [[String]]
var unitNr: Int
var lessonNr: Int
var unitLesson: Int
var practiceData: PracticeData
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let id = try container.decode(Int.self, forKey: .id)
self.id = id
self.word = try container.decode(String.self, forKey: .word)
self.meaning = try container.decode(String.self, forKey: .meaning)
self.pronunciationUrl = try container.decode(String.self, forKey: .pronunciationUrl)
self.similar = try container.decode([[String]].self, forKey: .similar)
self.unitNr = try container.decode(Int.self, forKey: .unitNr)
self.lessonNr = try container.decode(Int.self, forKey: .lessonNr)
self.unitLesson = try container.decode(Int.self, forKey: .unitLesson)
self.practiceData = PracticeData()
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id.self, forKey: .id)
try container.encode(word.self, forKey: .word)
try container.encode(meaning.self, forKey: .meaning)
try container.encode(pronunciationUrl.self, forKey: .pronunciationUrl)
try container.encode(similar.self, forKey: .similar)
try container.encode(unitNr.self, forKey: .unitNr)
try container.encode(lessonNr.self, forKey: .lessonNr)
try container.encode(unitLesson.self, forKey: .unitLesson)
try container.encode(practiceData.self, forKey: .practiceData)
}
private enum CodingKeys: CodingKey {
case id, word, meaning, pronunciationUrl, practiceData, similar, unitNr, lessonNr, unitLesson
}
}
func read(predicate: Predicate<Vocab>?,
sortDescriptors: SortDescriptor<Vocab>...) throws -> [Vocab] {
let context = ModelContext(self.container)
let fetchDescriptor = FetchDescriptor<Vocab>(
predicate: predicate,
sortBy: sortDescriptors
)
let fetchDescriptor2 = FetchDescriptor<Vocab>()
let nr = try context.fetchCount(fetchDescriptor)
do {
return try context.fetch(fetchDescriptor)
} catch {
print("Error reading from database")
return []
}
}
Why does context.fetchCount return the correct number of vocab objects, but fetch doesn’t return the objects? I get error Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1c29454b0) when I run this.
I tried removing the sorting and predicate, but that doesn’t change anything.