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

MapKit adding multiple annotations from core data

这是我的代码。它循环查找数据库中的数字记录,但只检索第一条记录纬度和经度。

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

}

我确信我遗漏了一些简单的东西,但只是继续遗漏它。

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

你可以这样做 for data in myData { ...

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

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