2014-01-07 64 views
0

我正在使用嵌入在導航控制器中的UITableView(與表格單元格)。當應用程序啓動時,將讀取SQLite3數據庫中的數據並將其添加到表格單元格中。UITableView重載 - Xcode 5

我做了一個按鈕(在導航欄上),它將引導用戶到他可以輸入新數據的屏幕。當用戶點擊「返回」時會發生'保存',這些按鈕由導航控制器自動添加。

當用戶返回到開始頁面時,數據未被重新加載,因此新條目在重新啓動應用程序之前不可見。

返回視圖時刷新數據的最佳方式是什麼?

#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 

新的數據在這裏補充說:

#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 = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
    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.."); 
    } 
} 

回答

4

你可以刷新你的tableview和數據模型在viewDidAppear方法,像這樣:

-(void)viewDidAppear:(BOOL)animated { 

    [super viewDidAppear:animated];  

    [self loadData]; 
    [self.myTableView reload]; 
} 
+0

太好了!只是數據每次都添加到我的數組中,所以我在我的列表中獲得重複條目。我應該每次清空陣列還是有其他方法? – Jente

+0

通過使數組變空來修復它。謝謝。 – Jente