Search code examples
iosviewdidloadviewdidappear

iOS: Running database query in viewDidLoad only works once


So let's see if I can write a clear enough description of my problem...

I'm developing an application for a museum, where the user can find artworks either through an id or by scanning a qr tag... Once either an id is entered or a tag scanned, the application sends the user from the search view, to the info view. The info view gathers information about the artwork from an SQLite database...

My problem is, that in the info view, I call the function from the database class as such:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSArray *paintingInfo = [[PaintingDatabase database] findPaintingByID];

    (additional code)
}

And I have no problem getting the info... works fine... But my problem is, that if I go back to the search view and enter a new id or scan a new tag, the call/search isn't run again, since the view is still in memory...

So, how would I go about running

NSArray *paintingInfo = [[PaintingDatabase database] findPaintingByID];

every time I enter the view...?

I've tried placing it in viewDidAppear instead, but I get an EXC_BAD_ACCESS error...


Solution

  • I think you are close to answering your own question. Since viewDidLoad only gets called when your view loads, if you are using the same ViewController you will not get the results you are looking for. One option may be to destroy and create a new ViewController each time. This probably would be acceptable, performance-wise. Another option (that you seem to have explored) is to put your code in viewWillAppear. I would probably look into this more, and figure out what is causing your crash.