问题
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