领域地图聚类

时间:2017-03-10 11:01:24

标签: swift swift3 realm

要创建您自己的数据以显示在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
    }
}

我想创建几个随机引脚,看看是否有效。 Atm我收到错误:

safeObject->_coordinate = coordinate;

线程9:EXC_BAD_ACCESS(代码= 1,地址= 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;
    }
)

然后我也将[{1}}添加到方法AppDelegate.swift中:

didFinishLaunchingWithOptions

错误:“主键属性'Test.id'在迁移后具有重复值。”

1 个答案:

答案 0 :(得分:2)

来自REALM文档。

  

重写Object.primaryKey()以设置模型的主键。声明   主键允许有效地查找和更新对象   并强制执行每个值的唯一性。一旦具有主要对象   key被添加到Realm中,主键无法更改。

如果您想创建自己的Realm模型,只需创建具有D[i,j]扩展名的类。

示例:

D[i,i]=0