【问题标题】:MapKit adding multiple annotations from core dataMapKit 从核心数据添加多个注释
【发布时间】:2025-12-22 22:10:12
【问题描述】:

这是我的代码。它循环查找数据库中的数字记录,但只检索第一个记录 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)
    }

}

我确定我错过了一些简单的东西,但一直错过它。

【问题讨论】:

    标签: swift core-data mapkit ios9 mapkitannotation


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

          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)
          }
      

      【讨论】: