MapKit adding multiple annotations from core data

爱⌒轻易说出口 提交于 2019-12-11 23:07:26

问题


This is my code. It loops for the number records in the database but only retrieves the first records lat and 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)
    }

}

I am sure I am missing something simple but just keep missing it.


回答1:


Your loop looks weird. You say myData[row], but you don't seem to increment the row. If the row does not increment, the data variable will always be the same.

You could do for example for data in myData { ...




回答2:


This is the code I ended up with to fix the issue.

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


来源:https://stackoverflow.com/questions/32938044/mapkit-adding-multiple-annotations-from-core-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!