我有一节课Place
&其他类为Address
。现在一个地方只有一个地址所以我创建了一个关系。现在我想保存这个地方然后我无法做到.Below是我为此写的代码功能。
if #available(iOS 10, *) {
placeInfo = NSEntityDescription.insertNewObject(forEntityName: "PlaceInfo", into: appDelegate.persistentContainer.viewContext) as? PlaceInfo
} else {
placeInfo = NSEntityDescription.insertNewObject(forEntityName: "PlaceInfo", into: appDelegate.managedObjectContext!) as? PlaceInfo
}
var cordinates:[String] = []
placeInfo?.title = Place.shared.title ?? ""
placeInfo?.desc = Place.shared.desc ?? ""
placeInfo?.id = "Place_" + String(Utility.shared.currentTimeStamp())
let spotLocation = Place.shared.address
if let lat = spotLocation?.lat, let long = spotLocation?.long {
cordinates = [lat.toString(),long.toString()]
}
let address = NSEntityDescription.insertNewObject(forEntityName: "PlaceAddress", into: appDelegate.managedObjectContext!) as? PlaceAddress
address?.street = "Street"
address?.landmark = "LANDMARK"
address?.city = "MYCITY"
address?.state = "SATTE"
address?.state = "INDIA"
address?.pincode = "1256325"
placeInfo?.isuploaded = true
if let spotid = placeInfo?.id {
// saveMediaToDB(id: spotid)
}
placeInfo?.address_rel = address
Placeinfo类
import Foundation
import CoreData
extension PlaceInfo {
@nonobjc public class func fetchRequest() -> NSFetchRequest<PlaceInfo> {
return NSFetchRequest<PlaceInfo>(entityName: "PlaceInfo")
}
@NSManaged public var desc: String?
@NSManaged public var hasmedia: Bool
@NSManaged public var id: String?
@NSManaged public var isuploaded: Bool
@NSManaged public var title: String?
@NSManaged public var address_rel: PlaceAddress?
@NSManaged public var files_rel: NSSet?
}
// MARK: Generated accessors for files_rel
extension PlaceInfo {
@objc(addFiles_relObject:)
@NSManaged public func addToFiles_rel(_ value: FilesInfo)
@objc(removeFiles_relObject:)
@NSManaged public func removeFromFiles_rel(_ value: FilesInfo)
@objc(addFiles_rel:)
@NSManaged public func addToFiles_rel(_ values: NSSet)
@objc(removeFiles_rel:)
@NSManaged public func removeFromFiles_rel(_ values: NSSet)
}
答案 0 :(得分:0)
您是否添加了以下代码行?
do {
try managedObjectContext.save()
} catch {
fatalError("Failure to save context: \(error)")
}