0
내비게이션 컨트롤러에 포함 된 UITableView (표 셀 포함)를 사용하고 있습니다. 앱이 시작되면 SQLite3 데이터베이스의 데이터가 읽고 테이블 셀에 추가됩니다.UITableView reload - 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..");
}
}
우수함! 매번 내 배열에 추가되는 데이터 만 있으므로 목록에 중복 항목이 생깁니다. 매번 배열을 비우거나 다른 방법으로 사용해야합니까? – Jente
배열을 비워서 고정했습니다. 고맙습니다. – Jente