0
我有一类Place
&其他类作为Address
。现在一个地方只有一个地址,所以我必须创造,当我试图挽救地方,那我不能够做一个relationship.Now。下面是代码我为这个功能写了。用关系类保存coredata中的数据?
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)
}
为什么你可选择downcast'as? PlaceInfo'和'as? PlaceAddress'?这些类在编译时肯定存在。强制downcast不能失败,否则会显示开发人员/设计错误。然后你摆脱所有难看的问号。你也应该为'PlaceAddress'初始值设定项执行条件编译'if #available(iOS 10,*)'。 – vadian