LoginSignup
5
4

More than 5 years have passed since last update.

【Objective-C】sqliteデータベースファイルをXcodeプロジェクトに埋め込む方法

Last updated at Posted at 2015-12-07
  • sqliteの導入方法は割愛

概要

毎回create databaseをやるのは面倒なので、sqliteファイルを初回起動時から既に用意しておく

前提

  • DBを使用するケース
  • sqliteファイルを初回起動時アプリ内に内包するため、ソース内からcreate databaseしない

手順

  • sqliteファイルを作成する
  • Xcodeのソースツリーにsqliteファイルをドロップし登録する
  • プロジェクト名 → Target → Build Phases → Link Binary With Librariesから該当のsqliteファイルを登録する
  • sqliteファイルオープン処理でdocumentフォルダにsqliteファイルをコピーする処理を記述する

以下記述例

SqliteManager.h
#import <Foundation/Foundation.h>
#import <sqlite3.h>
#import "FMDatabase.h"

@interface SqliteManager : NSObject

+ (BOOL) createDb;

SqliteManager.m
#import "SqliteManager.h"

@interface SqliteManager()

@end

static NSString* const DB_FILE = @"/app.sqlite";

@implementation SqliteManager

+ (BOOL)createDb {

    // document配下にパスを取得
    NSString *dbPath = nil;
    NSArray *documentsPath = NSSearchPathForDirectoriesInDomains
    (NSDocumentDirectory, NSUserDomainMask, YES);
    // 取得データ数を確認
    if ([documentsPath count] >= 1) {
        dbPath = [documentsPath objectAtIndex:0];
        // DBへのフルパスを生成。
        dbPath = [dbPath stringByAppendingPathComponent:DB_FILE];
        NSLog(@"DBPath : %@", dbPath);
    } else {
        //errorの場合
        NSLog(@"database file open error.");
        return NO;
    }

    // DBファイルがDocument配下に存在するか判定
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:dbPath]) {
        // アプリケーション内に内包したDBファイルをコピー(初回のみ)
        NSBundle *bundle = [NSBundle mainBundle];
        NSString *orgPath = [bundle bundlePath];
        // 初期ファイルのパス
        orgPath = [orgPath stringByAppendingPathComponent:DB_FILE];

        // アプリケーション内に内包したDBファイルをDocument配下へコピーする
        if (![fileManager copyItemAtPath:orgPath toPath:dbPath error:nil]) {
            //error
            NSLog(@"db file copy failed. : %@ to %@.", orgPath, dbPath);
            return NO;
        }
    }

    return YES;
}

補足

FMDBライブラリを利用しない場合も同様。

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4