Question

I'm using an UITableView (with a Table Cell) that's embedded in a navigation controller. When the app starts, data from the SQLite3 database is read and added in the table cells.

I've made a button (on the navigation bar) that will direct the user to a screen where he can input new data. The 'save' happens when the users clicks 'Back', the buttons that's automatically added by the navigation controller.

When the users returns to the start page, the data isn't being reloaded, so the new entry isn't visible until they restart the application.

What's the best way to refresh the data when they return to the view?

#import "lucidViewController.h"
#import "lucidCell.h"

@interface lucidViewController () {
}

@end

@implementation lucidViewController
@synthesize titleData,descrData,idKeyData;

- (void)viewDidLoad {
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;

    [self openDB];
    [self createTable:@"dreams" withField1:@"idKey" withField2:@"title" withField3:@"description"];

    titleData = [[NSMutableArray alloc] init];
    descrData = [[NSMutableArray alloc] init];
    idKeyData = [[NSMutableArray alloc] init];

    [self loadData];

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void) loadData {
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM dreams"];
    sqlite3_stmt *statement;

    if (sqlite3_prepare_v2(dataBase, [sql UTF8String], -1, &statement, nil) == SQLITE_OK) {
        while (sqlite3_step(statement) == SQLITE_ROW) {
            char *field1 = (char *) sqlite3_column_text(statement, 0);
            NSString *field1Str = [[NSString alloc]initWithUTF8String:field1];

            char *field2 = (char *) sqlite3_column_text(statement, 1);
            NSString *field2Str = [[NSString alloc]initWithUTF8String:field2];

            char *field3 = (char *) sqlite3_column_text(statement, 2);
            NSString *field3Str = [[NSString alloc]initWithUTF8String:field3];

            [idKeyData addObject:field1Str];
            [titleData addObject:field2Str];
            [descrData addObject:field3Str];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSString *) filePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [[paths objectAtIndex:0] stringByAppendingPathComponent:@"lucid.sql"];
}

- (void) openDB {
    if (sqlite3_open([[self filePath] UTF8String], &dataBase) != SQLITE_OK) {
        sqlite3_close(dataBase);
        NSAssert(0, @"Database kan niet geopend worden");
    } else {
        NSLog(@"Database is geopend!");
    }
}

- (void) createTable:(NSString *)tableName withField1:(NSString *)field1 withField2:(NSString *)field2 withField3:(NSString *)field3 {
    char *error;
    NSString *sqlStatement = [NSString stringWithFormat:
                              @"CREATE TABLE IF NOT EXISTS '%@'('%@' TEXT PRIMARY KEY, '%@' TEXT, '%@' TEXT);",tableName,field1,field2,field3];
    if (sqlite3_exec(dataBase, [sqlStatement UTF8String], NULL, NULL, &error) != SQLITE_OK) {
        sqlite3_close(dataBase);
        NSLog(@"Table kan niet aangemaakt worden..");
    } else {
        NSLog(@"Table aangemaakt!");
    }
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [titleData count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    lucidCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!Cell) {
        Cell = [[lucidCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    Cell.descrLabel.text = [self.descrData objectAtIndex:indexPath.row];
    Cell.titleLabel.text = [self.titleData objectAtIndex:indexPath.row];
    return Cell;
}
@end

The new data is added here:

#import "newViewController.h"

@interface newViewController ()

@end

@implementation newViewController
@synthesize addNewDream;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad {
    [self openDB];
    [self genRandStringLength:20];
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSString *) filePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [[paths objectAtIndex:0] stringByAppendingPathComponent:@"lucid.sql"];
}

- (void) openDB {
    if (sqlite3_open([[self filePath] UTF8String], &dataBase) != SQLITE_OK) {
        sqlite3_close(dataBase);
        NSAssert(0, @"Database kan niet geopend worden");
    } else {
        NSLog(@"Database is geopend!");
    }
}

-(NSString *) genRandStringLength: (int) len {
    NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity: len];

    for (int i=0; i<len; i++) {
        [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random() % [letters length]]];
    }
    return randomString;
}

- (void) viewWillDisappear:(BOOL)animated {
    NSString *dreamText = addNewDream.text;
    NSString *idKey = [self genRandStringLength:25];
    NSDate *myDate = [NSDate date];
    NSDateFormatter *df = [NSDateFormatter new];
    [df setDateFormat:@"dd/MM/yyyy, hh:mm"];
    NSString *title = [df stringFromDate:myDate];

    if (![dreamText isEqualToString:@""]){
        NSString *statement = [NSString stringWithFormat:@"INSERT INTO dreams ('idKey','title','description') VALUES ('%@','%@','%@')",idKey,title,dreamText];
        char *error;
        if (sqlite3_exec(dataBase, [statement UTF8String], NULL, NULL, &error) != SQLITE_OK) {
            sqlite3_close(dataBase);
            NSAssert(0, @"Kan niet wegschrijven naar tabel");
        } else {
            NSLog(@"Table write succesvol!");
        }
    } else {
        NSLog(@"Geen nieuwe droom ingevuld..");
    }
}
Was it helpful?

Solution

You could refresh your tableview and datamodel in your viewDidAppear method like so:

-(void)viewDidAppear:(BOOL)animated {

   [super viewDidAppear:animated];    

   [self loadData]; 
   [self.myTableView reload]; 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top