UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: CoreData losing its data

Forums > SwiftUI

Hello, I have many accesses to coreData from deferent views(save, delete,read), but sometimes, many views can not load its data until I restart the iphone. I mplemented the context as:

@Published var viewContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

and I use it for all operations, and I use viewContext.performAndWait for updating data.

    func updateStatus(post: Post) {
        let newStatus = vm.isBookmarked
        vm.viewContext.performAndWait {
                post.isBooked = newStatus
            try? vm.viewContext.save()
            }

        }

3      

Is it because the iphone storage almost full, or because I use the same context for all operations?

3      

hi,

i think you probably did not get any replies to this because there really is not much detail provided. for example, are you using @FetchRequest in any views, or is your view model using an NSFetchedResultsController?

but one comment: there's no reason to make the viewContext @Published in your view model (assuming you have one that is an @ObservableObject). the value of viewContext never changes -- but the objects in the context will change. that would explain your "can't see anything until you restart the iPhone" comment. (did you mean restart the app, or do you really have to restart the iPhone?)

hope that helps,

DMG

3      

Hi, I use @FetchRequest. I see all fetched data in all views normally, but somtimes I miss some views data. when I restsrt the app, these views still missing data until I restart my iphone.

3      

I solved it by fetching data like this:

let request = Post.fetchRequest() as NSFetchRequest<Post>
            FavPost = try viewContext.fetch(request)

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.