【发布时间】:2017-03-10 11:01:23
【问题描述】:
要创建您自己的数据以呈现在realm map 中,您需要模型,如示例所示:
public class ABFRestaurantObject: Object {
public dynamic var businessId: String?
public dynamic var name: String?
public dynamic var address: String?
public dynamic var city: String?
public dynamic var state: String?
public dynamic var postalCode: String?
public dynamic var latitude: Double = 37.7859547
public dynamic var longitude: Double = -122.4024658
public dynamic var phoneNumber: String?
public let violations = List<ABFViolationObject>()
public let inspections = List<ABFInspectionObject>()
override public static func primaryKey() -> String? {
return "businessId"
}
}
primaryKey 是什么意思?那我怎么能把我自己的数据加载进去呢?当然忽略您必须使用自定义属性创建自己的模型这一事实?
提前致谢!
编辑
我正在使用 Realm 地图套件聚类
我已经创建了模型:
class Test: Object {
public dynamic var id = 0
public dynamic var latitude = 45.0889
public dynamic var longitude = 54.1565
override static func primaryKey() -> String? {
return "id"
}
}
然后在我的地图控制器中,我添加了以下函数和声明:
var positions = try! Realm().objects(Test.self)
var position:Test!
override func viewDidLoad() {
super.viewDidLoad()
addNewVehicle()
populateMap()
}
func addNewPosition() {
let realm = try! Realm() // 1
try! realm.write { // 2
let newPos = Test() // 3
newPos.latitude = 50.060363
newPos.longitude = 19.939983
realm.add(newPos) // 5
self.position = newPos // 6
}
}
func populateMap() {
mapView.removeAnnotations(mapView.annotations) // 1
let positions = try! Realm().objects(Test.self) // 2
// Create annotations for each one
for pos in positions { // 3
let coord = CLLocationCoordinate2D(latitude: pos.latitude, longitude: pos.longitude);
let pin = MapPin(coordinate: coord, title: "asd", subtitle: "asd")
mapView.addAnnotation(pin) // 4
}
}
最后是创建引脚的简单类:
class MapPin : NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String?
var subtitle: String?
init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) {
self.coordinate = coordinate
self.title = title
self.subtitle = subtitle
}
}
我想创建一些随机引脚并查看 clustring 是否有效。 Atm 我收到一条错误消息:
safeObject->_coordinate = coordinate;
线程 9:EXC_BAD_ACCESS(code=1,address=0x40)
po positions
Results<Test> (
[0] Test {
latitude = 50.060363;
longitude = 19.939983;
},
[1] Test {
latitude = 50.060363;
longitude = 19.939983;
},
[2] Test {
latitude = 50.060363;
longitude = 19.939983;
}
)
然后我也将 AppDelegate.swift 添加到方法 didFinishLaunchingWithOptions 中:
let config = RLMRealmConfiguration.default()
config.schemaVersion = 1
config.migrationBlock = { (migration, oldSchemaVersion) in
}
RLMRealmConfiguration.setDefault(config)
错误:“主键属性 'Test.id' 在迁移后具有重复值。”
【问题讨论】:
-
请打印来自 Realm 的元素。它们不是空的吗?
-
已经有 3 个元素
-
我已经更新了我的新测试模型,在 appdelegate 中添加了新方法并得到了一个新错误;/
-
它应该是唯一的。 Id 已在测试中使用