我的核心数据项目中有2个实体:Land和Coordinate。 一块土地可以有很多坐标,所以它有一对多的关系。
为了保存我的土地及其坐标,我这样做:
func saveToDataBase() {
let landName:String = String(describing: Land.self)
let land:Land = NSEntityDescription.insertNewObject(forEntityName: landName, into: DatabaseController.getContext()) as! Land
land.id = 1
land.area = myLandArray[2]
land.perimeter = myLandArray[3]
land.lat = myLandArray[0]
land.long = myLandArray[1]
let coordName:String = String(describing: Coordinate.self)
let coord:Coordinate = NSEntityDescription.insertNewObject(forEntityName: coordName, into: DatabaseController.getContext()) as! Coordinate
for i in 0..<points.count {
coord.lat = points[i].latitude
coord.long = points[i].longitude
land.addToRelationship(coord) //add coordinates to its land
}
DatabaseController.saveContext()
}
我得到了这样的土地:
func showLands() {
let fetchRequest:NSFetchRequest<Land> = Land.fetchRequest()
do{
let searchResults = try DatabaseController.getContext().fetch(fetchRequest)
print("Number of results: \(searchResults.count)")
for result in searchResults as [Land]{
print("ID: \(result.id)")
print("Lat: \(result.lat)")
print("Long: \(result.long)")
print("Area: \(result.area) \(result.unArea!)")
print("Perimeter: \(result.perimeter) \(result.unPerimeter!)")
}
}
catch{
print("Error: \(error)")
}
}
如何获得每块土地的坐标?我尝试了一些没有成功的事情:(
以下是我的课程:
public class Coordinate: NSManagedObject {
}
extension Coordinate {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Coordinate> {
return NSFetchRequest<Coordinate>(entityName: "Coordinate");
}
@NSManaged public var id: Int64
@NSManaged public var lat: Double
@NSManaged public var long: Double
@NSManaged public var relationship: Land?
}
public class Land: NSManagedObject {
}
extension Land {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Land> {
return NSFetchRequest<Land>(entityName: "Land");
}
@NSManaged public var area: Double
@NSManaged public var attachment: NSData?
@NSManaged public var id: Int64
@NSManaged public var lat: Double
@NSManaged public var long: Double
@NSManaged public var perimeter: Double
@NSManaged public var relationship: NSSet?
}
// MARK: Generated accessors for relationship
extension Land {
@objc(addRelationshipObject:)
@NSManaged public func addToRelationship(_ value: Coordinate)
@objc(removeRelationshipObject:)
@NSManaged public func removeFromRelationship(_ value: Coordinate)
@objc(addRelationship:)
@NSManaged public func addToRelationship(_ values: NSSet)
@objc(removeRelationship:)
@NSManaged public func removeFromRelationship(_ values: NSSet)
}