简体   繁体   中英

In SwiftUI, how do I use FetchRequest results inside of init()?

How do I use FetchRequest results inside of init() ?

Code:

var noteObjectID: NSManagedObjectID
@FetchRequest var notes: FetchedResults<Note>
@State var noteBody: String = ""

init(noteObjectID: NSManagedObjectID) {
    self.noteObjectID = noteObjectID
    self._notes = FetchRequest(
        entity: Note.entity(),
        sortDescriptors: [],
        predicate: NSPredicate(format: "SELF == %@", noteObjectID)
    )
    self._noteBody = State(initialValue: self.notes.first?.body ?? "")
}

This causes the following error:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

This error is appearing at this line:

self._noteBody = State(initialValue: self.notes.first?.body ?? "")

I need this noteBody state variable for use with a TextField .

Just directly set the value:

init(noteObjectID: NSManagedObjectID) {
    super.init()
    self.noteBody = self.notes.first?.body ?? ""
}

The @State property wrapper will handle the rest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM