MapKit从核心数据中添加多个注释
问题描述:
这是我的代码。它循环查找数据库中的数字记录,但仅检索第一个记录lat和lon。MapKit从核心数据中添加多个注释
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)
}
}
我确定我缺少一些简单的东西,但只是不断丢失它。
答
这做的是我结束了解决问题的代码。
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)
}
答
你的循环看起来很奇怪。你说myData[row]
,但你似乎没有增加行。如果该行不增加,则data
变量将始终相同。
例如,您可以for data in myData { ...