SQLiteの利用2:DAOからのアクセス
前回のエントリーでSQLiteが使えるようになったので、DAOでアクセスできる形に整理してみました。ちょっと長いですが全コード掲載。最終的には下記のような構成になります。
DB関連ライブラリとファイルの準備
FMDBライブラリとlibsqlite3.0.dylib、データベースファイル(sample.db)をプロジェクトに追加します(参考:前回のエントリー)。今回は下記のテーブルを操作するためのクラスを追加してきます。
$ sqlite3 sample.db sqlite> CREATE TABLE TbNote( ...> id INTEGER PRIMARY KEY, ...> title VARCHAR(255), ...> body VARCHAR(255) ...> );
DTOを作成
作成したテーブルの内容を反映させます。テーブルの数だけクラスを作るので少々面倒ですが、携帯アプリでそんなに多くのテーブルを作成することもないと思うのでよしとします。intだけオブジェクトではないので少し扱い方が違います。
TbNote.h
#import <Foundation/Foundation.h> @interface TbNote : NSObject { int index; NSString *title; NSString *body; } @property (nonatomic, retain) NSString *title; @property (nonatomic, retain) NSString *body; - (id)initWithIndex:(int)newIndex Title:(NSString *)newTitle Body:(NSString *)newBody; - (int)getIndex; @end
TbNote.m
#import "TbNote.h" @implementation TbNote @synthesize title, body; - (id)initWithIndex:(int)newIndex Title:(NSString *)newTitle Body:(NSString *)newBody{ if(self = [super init]){ index = newIndex; self.title = newTitle; self.body = newBody; } return self; } - (int)getIndex{ return index; } - (void)dealloc { [title release]; [body release]; [super dealloc]; } @end
DAOを作成
FMDBのメソッドを実行する処理をDAOにまとめます。DBのインスタンスはAppDelegateから取得して初期化するのですが、これは全てのDAOで共通なので親クラスを作って実装します。-(NSString *)setTable:(NSString *)sql はSQLを実行する際にテーブル名をセットするメソッドです。
BaseDao.h
#import <Foundation/Foundation.h> @class FMDatabase; @interface BaseDao : NSObject { FMDatabase *db; } @property (nonatomic, retain) FMDatabase *db; -(NSString *)setTable:(NSString *)sql; @end
BaseDao.m
#import "SqlSampleAppDelegate.h" #import "FMDatabase.h" #import "FMDatabaseAdditions.h" #import "BaseDao.h" @implementation BaseDao @synthesize db; - (id)init{ if(self = [super init]){ // AppDelegateでオープン済みのDatabaseを取得 SqlSampleAppDelegate *appDelegate = (SqlSampleAppDelegate *)[[UIApplication sharedApplication] delegate]; db = [[appDelegate db] retain]; } return self; } // サブクラスで実装 -(NSString *)setTable:(NSString *)sql{ return NULL; } - (void)dealloc { [db release]; [super dealloc]; } @end
次にTbNoteテーブルにアクセスするクラスです。CRUD操作を一通り実装しています。
TbNoteDao.h
#import <Foundation/Foundation.h> #import "BaseDao.h" @interface TbNoteDao : BaseDao { } -(NSMutableArray *)select; -(void)insertWithTitle:(NSString *)title Body:(NSString *)body; -(BOOL)updateAt:(int)index Title:(NSString *)title Body:(NSString *)body; -(BOOL)deleteAt:(int)index; @end
TbNoteDao.m
#import "FMDatabase.h" #import "FMDatabaseAdditions.h" #import "TbNoteDao.h" #import "TbNote.h" @implementation TbNoteDao -(NSString *)setTable:(NSString *)sql{ return [NSString stringWithFormat:sql, @"TbNote"]; } // SELECT -(NSMutableArray *)select{ NSMutableArray *result = [[[NSMutableArray alloc] initWithCapacity:0] autorelease]; FMResultSet *rs = [db executeQuery:[self setTable:@"SELECT * FROM %@"]]; while ([rs next]) { TbNote *tr = [[TbNote alloc] initWithIndex:[rs intForColumn:@"id"] Title:[rs stringForColumn:@"title"] Body:[rs stringForColumn:@"body"] ]; [result addObject:tr]; [tr release]; } [rs close]; return result; } // INSERT -(void)insertWithTitle:(NSString *)title Body:(NSString *)body{ [db executeUpdate:[self setTable:@"INSERT INTO %@ (title, body) VALUES (?,?)"], title, body]; if ([db hadError]) { NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]); } } // UPDATE -(BOOL)updateAt:(int)index Title:(NSString *)title Body:(NSString *)body{ BOOL success = YES; [db executeUpdate:[self setTable:@"UPDATE %@ SET title=?, body=? WHERE id=?"], title, body, [NSNumber numberWithInt:index]]; if ([db hadError]) { NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]); success = NO; } return success; } // DELETE - (BOOL)deleteAt:(int)index{ BOOL success = YES; [db executeUpdate:[self setTable:@"DELETE FROM %@ WHERE id = ?"], [NSNumber numberWithInt:index]]; if ([db hadError]) { NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]); success = NO; } return success; } - (void)dealloc { [super dealloc]; } @end
TableViewに表示してみる
DB操作の動作確認用にUITableViewを追加します。initWithNibNameでDAOのテストを実行しています。この部分を動的に変更すれば簡単なメモ帳アプリを作れます。
NoteController.h
#import <UIKit/UIKit.h> @class TbNoteDao; @interface NoteController : UIViewController <UITableViewDataSource, UITableViewDelegate>{ UITableView *myTableView; TbNoteDao *tbNoteDao; NSMutableArray *record; } @property (nonatomic, retain) UITableView *myTableView; @property (nonatomic, retain) TbNoteDao *tbNoteDao; @property (nonatomic, retain) NSMutableArray *record; @end
NoteController.m
#import "NoteController.h" #import "TbNoteDao.h" #import "TbNote.h" @implementation NoteController @synthesize myTableView, tbNoteDao, record; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { tbNoteDao = [[TbNoteDao alloc] init]; [tbNoteDao insertWithTitle:@"TEST TITLE" Body:@"TEST BODY"]; // [tbNoteDao updateAt:1 Title:@"UPDATE TEST" Body:@"UPDATE BODY"]; // [tbNoteDao deleteAt:1]; record = [[tbNoteDao select] retain]; } return self; } - (void)viewDidLoad { [super viewDidLoad]; myTableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]]; myTableView.delegate = self; myTableView.dataSource = self; self.view = myTableView; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [record count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } // 該当するDTOにキャスト TbNote *tr = (TbNote *)[record objectAtIndex:indexPath.row]; cell.text = [NSString stringWithFormat:@"%i %@", [tr getIndex], tr.title]; return cell; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } - (void)dealloc { [super dealloc]; } @end
AppDelegate
最後にDBに接続する処理と、ViewControllerを追加する処理です。Interface Builderは利用しません。
SqlSampleAppDelegate.h
#import <UIKit/UIKit.h>
@class FMDatabase;
@interface SqlSampleAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
FMDatabase *db;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) FMDatabase *db;
- (BOOL)initDatabase;
- (void)closeDatabase;
@end
SqlSampleAppDelegate.m
#import "SqlSampleAppDelegate.h" #import "FMDatabase.h" #import "FMDatabaseAdditions.h" #import "NoteController.h" @implementation SqlSampleAppDelegate @synthesize window; @synthesize db; - (void)applicationDidFinishLaunching:(UIApplication *)application { if (![self initDatabase]){ NSLog(@"Failed to init Database."); } NoteController *ctrl = [[NoteController alloc] initWithNibName:nil bundle:nil]; [window addSubview:ctrl.view]; [window makeKeyAndVisible]; } // DBファイルのコピーとオープン - (BOOL)initDatabase{ BOOL success; NSError *error; NSFileManager *fm = [NSFileManager defaultManager]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"sample.db"]; success = [fm fileExistsAtPath:writableDBPath]; if(!success){ NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample.db"]; success = [fm copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; if(!success){ NSLog([error localizedDescription]); } success = NO; } if(success){ db = [[FMDatabase databaseWithPath:writableDBPath] retain]; if ([db open]) { [db setShouldCacheStatements:YES]; }else{ NSLog(@"Failed to open database."); success = NO; } } return success; } - (void) closeDatabase{ [db close]; } - (void)dealloc { [db release]; [window release]; [super dealloc]; } @end
本格的に利用しだすと上手く動作しない箇所があるかもしれませんが、今のところこんな感じです。サンプルコードはこちらからどうぞ。