也许我找不到这个问题的答案,因为它非常简单,我应该能够弄清楚,但我被难住了。哦,如果我的一些术语不正确,我很抱歉——我还在学习。
我使用的是Swift,并且有一个从Core Data派生的数组。到目前为止,一切都很好。该数组中的两个元素是Doubles/NSNumbers,用于存储纬度和经度。我将使用这两个元素在地图上绘制,但我不知道如何将这两个添加到自己的CLLocations数组中。
所以,我在核心数据中得到了所有数据的数组:
var locationsList: [Locations] = []
var context = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext!
var request = NSFetchRequest(entityName: "Locations")
let pred = NSPredicate(format: "game = %d", passedGameNumber)
request.predicate = pred
request.sortDescriptors = [NSSortDescriptor(key:"time", ascending: false)]
self.locationsList = context.executeFetchRequest(requestMap, error: nil)! as [Locations]
但它保存着核心数据中的所有数据(按游戏过滤):
class Locations: NSManagedObject {
@NSManaged var game: NSNumber
@NSManaged var time: NSDate
@NSManaged var latitude: NSNumber
@NSManaged var longitude: NSNumber
}
我只需要一个包含纬度和经度的数组,我需要将其转换为CLLocation才能放在地图上。我应该弄清楚地图的部分——正是这个阵列让我挠头!谢谢
想明白了。除了用于迭代核心数据数组的for循环之外,我还必须将纬度和经度转换为Doubles,然后将它们作为CLLocationCoordinate2D附加到我的新数组中。
var coordinates: [CLLocationCoordinate2D] = []
for index in 0..<self.locationsList.count{
var lat = Double(self.locationsList[index].latitude)
var long = Double(self.locationsList[index].longitude)
var coordinatesToAppend = CLLocationCoordinate2D(latitude: lat, longitude: long)
coordinates.append(coordinatesToAppend)
}
好的解决方案Adam。。。我也能做类似的事情。。
声明这些全局变量
var longitudeCollection: [String] = [String]()
var latitudeCollection: [String] = [String]()
做一个扩展,以方便访问CLLoationDegrees类型作为双
extension String {
var coordinateValue: CLLocationDegrees {
return (self as NSString).doubleValue
}
}
然后这就是你将如何附加坐标
for var index = 0; index<=longitudeCollection.count-1; index++ {
var lat = latitudeCollection[index].coordinateValue
var long = longitudeCollection[index].coordinateValue
var coordinatesToAppend = CLLocationCoordinate2D(latitude: lat, longitude: long)
coordinates.append(coordinatesToAppend)
}
您不需要使用NSNumber来存储纬度和经度点。您可以将CLLocation直接存储到核心数据中。
为每个CLLocation设置一个实体,无论哪个实体使用定位点,都会有太多的关系。让我们称之为LocationPoint:
class LocationPoint: NSManagedObject {
@NSManaged var game: NSNumber
@NSManaged var time: NSDate
@NSManaged var location: AnyObject
}
然后在Xcode数据模型中将location属性设置为transformable。就是这样!
在Objective-c中,您实际上仍然可以将此LocationPoint属性声明为CLLocation,而不会出现任何错误:
@property (nonatomic, strong) CLLocation *location