Please Enable JavaScript!
Gon[ Enable JavaScript ]

iPhone (아이폰) 개발시 DB를 위한 Sqlite3 다루기 (2)

안드로이드 개발
반응형

iPhone (아이폰) 개발시 DB를 위한 Sqlite3 다루기 (2)

 

개발환경 : Mac OS X 10.6.3, Simulator - 3.1.3

 

전편에서 작성한 sqlite3 파일을 어떻게 프로젝트에 넣고 사용하는지에 대한

설명을 했었다. 이번에는 여기에 테이블을 만들고 데이터를 집어 넣은후

그 내용을 가져와서 테이블 형태로 보여주는 프로그램을 구현해볼 것이다.

 

퀴즈 관련 테이블을 만든다.

CREATE TABLE "quiz" ("no" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL ,

"title" VARCHAR, "question" VARCHAR, "answer" VARCHAR, "level" VARCHAR)

 

이 테이블의 용도는 퀴즈 문제를 DB 에 넣어두고 문제풀이를 위한 어플을 만드는데

쓰일것이다. 아무것도 없으므로 샘플데이타를 집어넣어 준다.

[샘플 insert 쿼리문]

insert into quiz (title, question, answer, level) values ('title', '질문이다', '대답이다', '1')

insert into quiz (title, question, answer, level) values ('title2', '질문이다2', '대답이다2', '2')

insert into quiz (title, question, answer, level) values ('title3', '질문이다3', '대답이다3', '3')

 

데이터베이스 테이블에 매칭되는 모델클래스를 하나만든다. Subclass NSObject

된다.

테이블을 표시할 UIViewController 의 첫 로딩함수에 데이터베이스 생성과 데이터를

불러올 함수를 집어넣는다.

dbName sqlite3 파일명을 말하며, dbPath 는 파일이 있는 위치를 저장한다.

quizs quiz 모델객체가 저장될 클래스 이다. 그리고 함수가 2개 있는데

checkAndCreateDatabase 는 지정한 DB 파일명이 있는지 체크하고 있으면

그냥넘어가지만 없으면 에러를 출력하게 되어있다. 두번째 readFromDatabase

현재 quiz 테이블에 저장된 데이터를 모두 가져와 quizs 에 저장하는

임무를 맡고 있다.

 

MainXib.h

@interface MainXib : UIViewController {
	NSString *path;
	NSString *dbName;
	NSString *dbPath;
	
	NSMutableArray *quizs;
}

@property(nonatomic, retain)NSMutableArray *quizs;

- (void)checkAndCreateDatabase;
- (void)readFromDatabase;

@end

UIViewController 을 상속받아 만든 클래스이므로 화면이 로딩되면 처음으로

실행되는 함수가 viewDidLoad 이다. 여기에 데이터베이스를 체크하고

내용을 가져오는 내용이 들어가 있다.

MainXib.m

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    dbName = @"success.sqlite";

    // Get the path to the documents directory and append the databaseName
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                      NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    dbPath = [documentsDir stringByAppendingPathComponent:dbName];
    
    // Execute the "checkAndCreateDatabase" function
    [self checkAndCreateDatabase];
    
    // Query the database for all animal records and construct the "animals" array
    [self readFromDatabase];
    [super viewDidLoad];
}

이제 테이블에 내용을 뿌려보도록 한다. 인터페이스 빌드에서 UITableView 를 넣고

델리게이트와 데이터소스를 연결 했다면 필수 구현함수 두가지를 작성해야한다.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section


아래의 내용은 그 두개의 함수에 구현된 내용이다. 소스를 보면 알겠지만

행에 집어넣을 데이터는 quiz 테이블의 title 필드이다.

// 셀을 넣는다
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	static NSString* cellIdentifier = @"cell";
	
	UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	
	// 이셀객체를 생성한다.
	if (cell == nil) {
		cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	}
	
	QuizDTO *quiz = [quizs objectAtIndex:indexPath.row];
	cell.textLabel.text = quiz.title;
	
	return cell;
}

// 각테이블의 섹션을 리턴한다.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	return quizs.count;
}

소스가 다 작성이 되었다면 실행을 시켜본다. 첫번째 그림은 파이어폭스에서

select 쿼리를 날려 본 데이터이고 두번째는 프로그램을 돌렸을 때 화면에 표시된

내용이다
반응형
Posted by 녹두장군1
,