Data not load if FetchResults in init() methods

If I use the following code, the project works normal.

let listRequest = FetchRequest<ReminderList>(entity: ReminderList.entity(), sortDescriptors: [NSSortDescriptor(key: "title", ascending: true)])

 var lists: FetchedResults<ReminderList>  {
        return listRequest.wrappedValue
    }

But if I put lists variable in init() method (the following), the data not load. I don't know why.

let listRequest = FetchRequest<ReminderList>(entity: ReminderList.entity(), sortDescriptors: [NSSortDescriptor(key: "title", ascending: true)])

var lists: FetchResults<ReminderList>

init() {
   self.lists = listRequest.wrappedValue
}

Answered by deeje in 687212022

we're only getting a glimpse into your code, but my guess is that, when declared as vars, they are instantiated when the struct/object is created and don't have access to the environment variables such as "managedObjectContext". you might try using lazy?

Accepted Answer

we're only getting a glimpse into your code, but my guess is that, when declared as vars, they are instantiated when the struct/object is created and don't have access to the environment variables such as "managedObjectContext". you might try using lazy?

Data not load if FetchResults in init() methods
 
 
Q