MapKit从核心数据中添加多个注释

时间:2015-10-04 20:28:49

标签: swift core-data mapkit ios9 mapkitannotation

这是我的代码。它循环访问数据库中的数字记录,但只检索lat和lon的第一个记录。

    func fetch() {
    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context: NSManagedObjectContext = appDel.managedObjectContext!
    let freq = NSFetchRequest(entityName: "Mappoints")
    let fetchResults = try! context.executeFetchRequest(freq) as! [NSManagedObject]
    self.mapView.delegate = self
    myData = fetchResults
    myData.count
    for _ in myData  {
        let data: NSManagedObject = myData[row]

    lat = (data.valueForKey("latitude") as? String)!
    lon = (data.valueForKey("longitude") as? String)!

    let latNumb = (lat as NSString).doubleValue
    let longNumb = (lon as NSString).doubleValue
    let signLocation = CLLocationCoordinate2DMake(latNumb, longNumb)
    addAnnotaion(signLocation)
    }

}

我确信我错过了一些简单的东西,但只是一直想念它。

2 个答案:

答案 0 :(得分:1)

你的循环看起来很奇怪。你说myData[row],但你似乎没有增加行。如果行没有增加,data变量将始终相同。

你可以做例如for data in myData { ...

答案 1 :(得分:0)

这是我最终解决问题的代码。

    func fetch() {
    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context: NSManagedObjectContext = appDel.managedObjectContext!
    let freq = NSFetchRequest(entityName: "Mappoints")
    let fetchResults = try! context.executeFetchRequest(freq) as! [NSManagedObject]
    self.mapView.delegate = self
    myData = fetchResults
    let ct = myData.count // Add this line
    // Then changed the for statement from for _ in myData
    // To the line below and now all map points show up.
    for row in 0...ct-1 {
        let data: NSManagedObject = myData[row]
        lat = (data.valueForKey("latitude") as? String)!
        lon = (data.valueForKey("longitude") as? String)!
        let latNumb = (lat as NSString).doubleValue
        let longNumb = (lon as NSString).doubleValue
        let signLocation = CLLocationCoordinate2DMake(latNumb, longNumb)
        addAnnotaion(signLocation)
    }