2016-07-31 106 views
0

我是新來的領域,所以當我與它混在一起學習它時,我發現了一些非常有趣的東西。在我的appDelegate:領域設置自定義fileURL混淆

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:

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) 

} 

通知從打印的回報()函數。在應用程序委託中,打印結果(用戶數:)會返回0,但在viewController的viewDidLoad中,它返回1.

是不是都應該返回相同的值?在這種情況下1?

在此先感謝!

回答

1

是的,它是一樣的,我猜你刪除錯誤的用戶,應用程序負載,或類似的東西,你應該使用「境界的瀏覽器」,檢查您的數據庫狀態,這樣你可以看到當對象在運行時更改。 https://github.com/realm/realm-browser-osx

編輯

檢查您訪問的默認配置。在境界,你可以有多種配置,像這樣:

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

嗨,感謝您的建議。我發現ViewController的Realm的fileURL是default.realm,而不是分配的App Group。爲什麼?再次感謝!! –

+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 
    }