我是新手,所以当我为了学习它而愚弄时,我发现了一些非常有趣的东西。在我的appDelegate中:
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)
}
注意print()函数的返回值。在app delegate中,print的结果(用户数:)返回0,但是在viewController的viewDidLoad中,它返回了1。
两者都不应该返回相同的值吗?在这种情况下1?
提前致谢!!
答案 0 :(得分:1)
是的,它是一样的,我猜你错误地删除了用户,在应用程序加载时,或类似的东西,你应该使用“Realm浏览器”检查你的数据库状态,这样你就可以看到一个对象运行时更改。 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)
答案 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
}