【发布时间】:2018-03-06 00:26:33
【问题描述】:
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”的类并运行我的代码,但之后它显示了这个错误。
2017-09-25 10:54:07.218441+0530 NewLogin[2264:51915] [MC] 系统组 systemgroup.com.apple.configurationprofiles 路径的容器是 /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] 阅读自 私人有效用户设置。
2017-09-25 10:54:18.146 NewLogin[2264:52118] Realm 2.10.1 版现已推出:https://github.com/realm/realm-cocoa/blob/v2.10.1/CHANGELOG.md
致命错误:“试试!”表达式意外引发错误:错误 Domain=io.realm Code=10 "由于以下原因需要迁移 错误: - 属性 'Employee.salary' 已从 'int' 更改为 'string'。” UserInfo={NSLocalizedDescription=迁移是必需的,因为 以下错误: - 属性“Employee.salary”已从“int”更改为“string”。错误代码=10}:文件 /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-802.0.53/src/swift/stdlib/public/core/ErrorType.swift, 第 182 行
【问题讨论】:
-
你可以在这个答案中找到我的解决方案:https://stackoverflow.com/a/53979285/6013170