この記事について
| 環境 | Xcode、Objective-C、FMDB、SQLite |
|---|---|
| 目的 | FMDBでテーブル内の情報を出力する |
| 結果 | FMDatabaseでDocumentsのtest.dbを開き、executeQueryの結果をラベルや配列に出力できた |
つまずきポイント要約
- 結果を入れる配列は必ずNSMutableArrayで宣言する(NSArrayは不可)
- DBファイルはSupporting Filesに置いて起動時にDocumentsへコピーする方式が楽
FMDBでテーブル内の情報を出力するソースコード
前提として- FMDBが導入されている(導入方法はこちら)。
- test.dbというファイルが iOS Simulator の Documents ディレクトリにある(iOS Simulatorのパスについてはこちら)。このディレクトリに直接データファイルを置くと、シミュレーターのバージョンごとにデータファイルを置く必要があるので面倒。解決策として、Supporting Files 内にデータファイルを置いておいて、アプリ起動時に Supporting Files 内にデータがない場合に Documents ディレクトリにコピーする方法がある。詳しくは、こちら
- title というカラムにデータが既に入っている
ソースコード
//インポート(ヘッダーファイル)
#import "FMDatabase.h"
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// パスとDBファイル名を指定
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *dir = [paths objectAtIndex:0];
//test.db はファイル名
NSString *db_path = [dir stringByAppendingPathComponent:@"test.db"];
FMDatabase *db = [FMDatabase databaseWithPath:db_path];
//データを抽出
[db open];
//testdb はテーブル名
FMResultSet *rs = [db executeQuery:@"select id,title from testdb"];
while ([rs next]){
// 出力
NSString *text1 = [rs stringForColumn:@"title"];
//UIlabelクラスのインスタンスを生成。
//alloc でインスタンスの生成(allocationはメモリの割り当ての意)。init で初期化。
UILabel *label = [[UILabel alloc] init];
//labelオブジェクトにテキストを設定
label.text = text1;
//コンテンツの大きさに合わせてUIViewの大きさを変える。UIViewはUIlabelの親クラス。
[label sizeToFit];
//行数の指定。0は、表示可能な最大行数。(インスペクターでの設定も可だがソースが優先される)
label.numberOfLines = 0;
label.center = self.view.center;
[self.view addSubview:label];
// 出力 ここまで
}
[rs close];
}
結果をラベルに表示せずに、配列に入れる場合はスクリプト後半を以下のように変更する
//データを抽出
[db open];
FMResultSet *rs = [db executeQuery:@"select id,title from testdb"];
while ([rs next]){
// 出力
NSString *text1 = [rs stringForColumn:@"title"];
//配列を追加。配列の型は必ず NSMutableArray であること。NSArray は不可。
[testArray addObject:text1];
//UIlabelクラスのインスタンスを生成。
//alloc でインスタンスの生成(allocationはメモリの割り当ての意)。init で初期化。
// UILabel *label = [[UILabel alloc] init];
//labelオブジェクトにテキストを設定
//label.text = text1;
//コンテンツの大きさに合わせてUIViewの大きさを変える。UIViewはUIlabelの親クラス。
//[label sizeToFit];
//label.center = self.view.center;
//[self.view addSubview:label];
// 出力 ここまで
}
[rs close];
