Question

Overview

I have an iOS project in which I store a list of names in a table view.

I understand the moment the database is opened / created, there is a completion handler to execute a method.

Steps:

  1. In my case, the first screen is a table view which displays the names
  2. there is a + button (on the navigation bar) to add a new name which would take it to a new screen to enter the details.

Concern

My worry is that if I fetch the names for the tableview in the completion handler and if the user doesn't wait for the database to be opened and creates a new name, while saving it, the database might not be opened / created.

Questions

  1. How to handle such a situation ?
  2. Am I missing something ?
Was it helpful?

Solution

Really, you should not be allowing the user to change stuff until everything is initialized. If it takes a while, then just disable that functionality until ready.

In this case it's easy. Start with the "add" button disabled, and enable it in the completion handler.

You can write a documentIsReady method (which will enable editing, and anything else you want to do when "all is ready."), and then call it when the document is ready to be used. See code below for example.

    if (![[NSFileManager defaultManager] fileExistsAtPath:[doc.fileURL path]]) {
        [doc saveToURL:doc.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
            [self documentIsReady: success];
        }];
    } else if (doc.documentState == UIDocumentStateClosed) {
        [doc openWithCompletionHandler:^(BOOL success) {
            [self documentIsReady: success];
        }];
    } else {
        BOOL success = doc.documentState == UIDocumentStateNormal;
        [self documentIsReady: success];
    }

OTHER TIPS

Well, one (simple) way of handling this situation as add a timer to wait until the database is opened / created. You could also grey the button (the + button) out until the database is ready.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top