2016-07-31 5 views
0

私はレルムには新しいので、それを学ぶためにだまされていたので、かなり興味深いものが見つかりました。お知らせレルム設定カスタムファイルURL混乱

let realm = try! Realm() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    print("NO OF USERS IN VIEWDIDLOAD: \(realm.objects(User).count)") // -> 1 

    let firstTime = loadFirstTime() 
    if firstTime { 
     // configure USER! 
     let user = User() 
     user.monthlyIncome = 50000 
     try! realm.write({ 
      realm.add(user) 
     }) 
     saveFirstTime(false) 
     print("First time, user written") 
    } 
    dailyLimit.text = String(realm.objects(User).first!.dailyLimit) 

} 

印刷()関数からの戻り値:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
    let directory: NSURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.Hobo.RealmDatabase")! 
    var config = Realm.Configuration() 
    config.fileURL = directory.filePathURL?.URLByAppendingPathComponent("db.realm") 
    Realm.Configuration.defaultConfiguration = config 
    let realm = try! Realm() 
    print("File Location: \(realm.configuration.fileURL!)") // -> Location A 
    print("NO OF USERS: \(realm.objects(User).count)") // -> 0 
    return true 
} 

が、私のViewControllerで:私のappDelegateで。アプリケーションデリゲートでは、印刷結果(ユーザー数:)は0を返しますが、viewControllerのviewDidLoadでは1を返しました。

どちらも同じ値を返すとは限りませんか?この場合1?

ありがとうございます!

答えて

1

はい、私は間違ってユーザーやアプリケーションの負荷などで削除していると思いますが、 "Realm browser"を使用してDBの状態を確認してください。オブジェクトは実行時に変更されます。 https://github.com/realm/realm-browser-osx

EDIT

は、あなたがデフォルトの設定にアクセスして確認してください。分野では、そうのような複数の構成を持つことができます。

let config = Realm.Configuration(
    // Get the URL to the bundled file 
    fileURL: NSBundle.mainBundle().URLForResource("MyBundledData", withExtension: "realm"), 
    // Open the file in read-only mode as application bundles are not writeable 
    readOnly: true) 

// Open the Realm with the configuration 
let realm = try! Realm(configuration: config) 
+0

のHiの文書に提案に感謝を依存しています。私は、ViewControllerのRealmのfileURLが、割り当てられたApp Groupではなくdefault.realmであることを理解しました。どうしてこんなことに?再度、感謝します!! –

+0

@RaymondMoay私は答えを編集しました – MCMatan

+1

ありがとう!解決済み。 (: –

0

は、領域3

https://realm.io/docs/swift/latest/#realm-configuration

func setDefaultRealmForUser(username: String) { 
     var config = Realm.Configuration() 

     // Use the default directory, but replace the filename with the username 
     config.fileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("\(username).realm") 

     // Set this as the configuration used for the default Realm 
     Realm.Configuration.defaultConfiguration = config 
    }