我正在尝试加载预先填充的领域数据库:
数据库看起来像这样: Image Link
我将文件拖到Xcode管理中,如下所示: Message Link
然后我的项目树看起来像这样:Project Tree Link
在Swift中,AppDelegate中的以下代码用于迁移
import UIKit
import RealmSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let defaultPath = Realm.Configuration.defaultConfiguration.fileURL
let oldPath = Bundle.main.url(forResource: "person", withExtension: "realm")
if let bundlePath = oldPath {
do {
try? FileManager.default.removeItem(at: defaultPath!)
try FileManager.default.copyItem(at: bundlePath, to: defaultPath!)
} catch {
print(error)
}
}
let config = Realm.Configuration(
schemaVersion: 2,
migrationBlock: { migration, oldSchemaVersion in
if oldSchemaVersion < 1 {
migration.enumerateObjects(ofType: Book1.className(), { (oldObject, newObject) in
let answer = oldObject!["answer"] as! String?
let name = oldObject!["name"] as! String?
newObject?["answer"] = answer
newObject?["name"] = name
})
}
}, deleteRealmIfMigrationNeeded: false, objectTypes: [Book1.self])
Realm.Configuration.defaultConfiguration = config
// Override point for customization after application launch.
return true
}
这是Book1课程:
import Foundation
import RealmSwift
class Book1: Object {
@objc dynamic var name: String? = nil
@objc dynamic var answer: String? = nil
}
这是ViewController中包含表格的代码:
import UIKit
import RealmSwift
class ViewController: UIViewController {
@IBOutlet weak var myTable: UITableView!
let cellID = "cell"
var realm: Realm!
var output : Results<Book1> {
return realm.objects(Book1.self)
}
override func viewDidLoad() {
super.viewDidLoad()
realm = try! Realm()
}
}
// MARK: Table
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return output.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)
cell.textLabel?.text = output[indexPath.row].name
return cell
}
}
当我运行应用程序时,出现以下错误
线程1:致命错误:'试试!'表达式意外地引发了错误:错误Domain = io.realm Code = 1“Property'Book1.name'不存在”UserInfo = {NSLocalizedDescription = Property'Book1.name'不存在,错误代码= 1}
知道为什么吗?我检查了应用程序复制的默认数据库,它是正确的数据库。