LoginSignup
56
53

More than 5 years have passed since last update.

Swift + Realm DB をCocoaPodsで導入する手順

Last updated at Posted at 2015-01-08

MacにCocoaPodsをインストール

  1. gemをインストール

    sudo gem install cocoapods
    

    プレリリースのベータ版が必要になることがあるので、念のため併せてインストール

    gem install cocoapods --pre
    
  2. terminalを再起動する

    忘れがちです。
    再起動後にバージョンを確認しインストールされていることを確認します

    pod -v
    
  3. Set Up

    pod setup
    

Xcode Projectを作成

Swiftのプロジェクトを作成します
説明のため名前をSampleとします

Xcode ProjectにCocoaPodsを導入する

  1. Xcodeで作成したプロジェクトのディレクトリに移動

    cd project root directory
    ls -la
        Sample
        Sample.xcodeproj
        SampleTests
    
  2. CocoaPodsを初期化

    pod init
    

    Podfileが作成されます

  3. Podfileの編集

    target 'Sample', exclusive: true do
        pod 'Realm'
    end
    
    target 'SampleTests', exclusive: true do
        pod 'Realm/Headers'
    end
    

    ブロックを用いて、ターゲットごとにインストールするpodを分けることが出来ます。
    exclusive: trueとすると、ブロック内のpodのみしかインストールしないようになります。

  4. インストール
    pod initしたディレクトリと同じ場所で以下のコマンドを実行

    pod install
    
  5. Xcodeのプロジェクトを一旦閉じて、Sample.xcworkspaceという名前のプロジェクトを開きます。

    この時点で、Realm DBの導入自体は終了です。

SwiftでのRealm DBの利用

CocoaPodsでインストールしたRealm DBはObjective-Cで書かれているので、
Swiftのプロジェクトでも利用するためにBridging Headerファイルを追加します。
以下のヘッダファイルをプロジェクトに追加します。
Sample-Bridging-Header.h

  1. 以下の行を追記

    Sample-Bridging-Header.h
    #import <Realm/Realm.h>
    
  2. プロジェクトのBuild Settings -> swift compiler

    Objecctive-C Bridging headerの項目に

    Sample/Sample-Bridging-Header.h
    

    を追加する。パスを間違えやすいので注意してください。環境によっては別の階層かもしれません。

  3. 確認
    swiftのファイルに

    RLMObject()
    

    等と書いてエラーにならなければ正しく導入できています。

56
53
3

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
56
53