import UIKit
import Realm
import RealmSwift
class Employee: Object {
dynamic var name = ""
dynamic var salary = 0
}
class Emp: Object{
dynamic var name = ""
dynamic var salary = ""
}
class RealMEx: UIViewController,UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var txt1: UITextField!
@IBOutlet weak var txt2: UITextField!
@IBOutlet weak var tblView: UITableView!
var dataArry = [[String: Any]]()
@IBAction func Submit(_ sender: UIButton) {
let emp = Employee()
emp.name = txt1.text!
emp.salary = Int(txt2.text!)!
let realm = try! Realm()
try! realm.write {
realm.deleteAll()
realm.add(emp)
}
let data = realm.objects(Employee.self)
for i in Array(data){
let d = ["name":i["name"]!,"salary": i["salary"]!]
dataArry.append(d as [String : Any])
}
print (Array(data))
tblView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
tblView.delegate = self
tblView.dataSource = self
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArry.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)as! RealMTableCell
cell.lbl.text = dataArry[indexPath.row]["name"] as? String
cell.sallbl.text = dataArry[indexPath.row]["salary"] as? String
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我試圖創建簡單的領域對象來存儲和檢索數據,所以首先我寫了這段代碼,首先我用兩個不同的數組來存儲我的數據,但後來我把關聯數組。但是使用關聯數組我無法在表格視圖中打印我的「工資」。 所以我帶了另一個名爲「Emp」的類並運行我的代碼,但在此之後它向我顯示了這個錯誤。在swift中創建領域對象時出錯
2017-09-25 10:54:07.218441+0530 NewLogin[2264:51915] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/admin/Library/Developer/CoreSimulator/Devices/9F794470-A0F6-4D8F-8A4C-9CBF6852EE71/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2017-09-25 10:54:07.239924+0530 NewLogin[2264:51915] [MC] Reading from private effective user settings.
2017-09-25 10:54:18.146 NewLogin[2264:52118] Version 2.10.1 of Realm is now available: https://github.com/realm/realm-cocoa/blob/v2.10.1/CHANGELOG.md
fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=10 "Migration is required due to the following errors: - Property 'Employee.salary' has been changed from 'int' to 'string'." UserInfo={NSLocalizedDescription=Migration is required due to the following errors: - Property 'Employee.salary' has been changed from 'int' to 'string'., Error Code=10}: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-802.0.53/src/swift/stdlib/public/core/ErrorType.swift, line 182