我为每首歌曲创建了两个NSManagedObject
类,一个用于Songs
,一个用于Categories
。他们之间存在一对多的关系。我要做的是,我从服务器上下载了一个json
文件,并使用Decodable
对其进行了解析,然后将数据保存在CoreData中。一切都很顺利,除了当我尝试将歌曲添加到特定类别类型时,都会崩溃。
“在不同上下文中非法尝试在对象之间建立关系”类别”
我知道这次崩溃是什么,我知道我有两个上下文,一个是类别类,另一个是歌曲类。问题在于使用Decodable编写CoreData的教程太少了。因此,现在我正在考虑一种方法,也许可以创建这些类的父类并在其中创建上下文init
,然后在类别和歌曲的子类中调用super.init()
。但是我真的做不到。或者,也许有一种更简单的方法。我将在这里共享我的类的代码以及发生错误的代码。
struct CategoryData: Decodable {
let data: [CategoryManagedObject]
}
@objc(CategoryManagedObject)
class CategoryManagedObject: NSManagedObject, Decodable {
// MARK: - Core Data Managed Object
@NSManaged var id: Int
@NSManaged var name: String
@NSManaged var imgUrl: String
@NSManaged var coverPhotoBit64: String
@NSManaged var jsonUrl: String
@NSManaged var version: Int
@NSManaged var order: Int
@NSManaged var songs: NSSet?
//var coreDataStack: CoreDataManager!
enum CodingKeys: String, CodingKey {
case name, coverPhotoBit64, id, jsonUrl, version, order
case imgUrl = "coverPhoto"
}
// MARK: - Decodable
required convenience init(from decoder: Decoder) throws {
//try super.init(from: decoder, type: "Categories")
guard let codingUserInfoKeyManagedObjectContext = CodingUserInfoKey.context,
let managedObjectContext = decoder.userInfo[codingUserInfoKeyManagedObjectContext] as? NSManagedObjectContext,
let entity = NSEntityDescription.entity(forEntityName: "Categories", in: managedObjectContext) else {
fatalError("FALIED TO DECODE CATEGORIES")
}
self.init(entity: entity, insertInto: managedObjectContext)
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
name = try container.decode(String.self, forKey: .name)
imgUrl = try container.decode(String.self, forKey: .imgUrl)
coverPhotoBit64 = try container.decode(String.self, forKey: .coverPhotoBit64)
version = try container.decode(Int.self, forKey: .version)
jsonUrl = try container.decode(String.self, forKey: .jsonUrl)
order = try container.decode(Int.self, forKey: .order)
// if let sArray = songs.allObjects as? [Song] {
// songs = try container.decode(sArray.self, forKey: .song)
// }
}
@nonobjc public class func fetchRequest() -> NSFetchRequest<CategoryManagedObject> {
return NSFetchRequest<CategoryManagedObject>(entityName: "Categories")
}
}
public extension CodingUserInfoKey {
// Helper property to retrieve the context
static let context = CodingUserInfoKey(rawValue: "managedObjectContext")
}
// MARK: Generated accessors for songs
extension CategoryManagedObject {
@objc(addSongsObject:)
@NSManaged public func addToSongs(_ value: Song)
@objc(removeSongsObject:)
@NSManaged public func removeFromSongs(_ value: Song)
@objc(addSongs:)
@NSManaged public func addToSongs(_ values: NSSet)
@objc(removeSongs:)
@NSManaged public func removeFromSongs(_ values: NSSet)
}
@objc(Song)
public class Song: NSManagedObject, Decodable {
@NSManaged var id: Int
@NSManaged var name: String
@NSManaged var artist: String
@NSManaged var code: String
@NSManaged var category: CategoryManagedObject
enum CodingKeys: String, CodingKey {
case name, id, artist, code
}
// MARK: - Decodable
required convenience public init(from decoder: Decoder) throws {
guard let codingUserInfoKeyManagedObjectContext = CodingUserInfoKey.context,
let managedObjectContext = decoder.userInfo[codingUserInfoKeyManagedObjectContext] as? NSManagedObjectContext,
let entity = NSEntityDescription.entity(forEntityName: "Songs", in: managedObjectContext) else {
fatalError("FALIED TO DECODE CATEGORIES")
}
self.init(entity: entity, insertInto: managedObjectContext)
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
name = try container.decode(String.self, forKey: .name)
artist = try container.decode(String.self, forKey: .artist)
code = try container.decode(String.self, forKey: .code)
}
@nonobjc public class func fetchRequest() -> NSFetchRequest<Song> {
return NSFetchRequest<Song>(entityName: "Songs")
}
}
这是由于两个不同的上下文而导致崩溃的地方。
func saveJsonSongsInDB(filename fileName: String, category: CategoryManagedObject) {
do {
let data = try Data(contentsOf: URL(string: fileName)!)
//let context = CoreDataManager.shared.persistentContainer.newBackgroundContext()
let decoder = JSONDecoder()
decoder.userInfo[CodingUserInfoKey.context!] = dbContext
//decoder.userInfo[CodingUserInfoKey.deferInsertion] = true
coreDataStack.deleteAllRecords("Songs")
let songs = try decoder.decode([Song].self, from: data)
let s = NSSet(array: songs)
// category.managedObjectContext?.insert(<#T##object: NSManagedObject##NSManagedObject#>)
// dbContext.insert(category)
//print("SONGS: \(songs)")
category.addToSongs(s) //----> CRASH
try dbContext.save()
} catch let err {
print("error:\(err)")
}
}
答案 0 :(得分:0)
首先使用一个上下文,该上下文在JSONDEcoder
在CategoryManagedObject
中将songs
声明为非可选本机类型
@NSManaged var songs: Set<Song>
将songs
解码为Set
(是的,这是可能的),并将每首歌曲的类别设置为self
songs = try container.decode(Set<Song>.self, forKey: .song)
songs.forEach{ $0.category = self }
仅此而已。您不必在CategoryManagedObject
要插入数据,您必须解码[CategoryManagedObject]
let decoder = JSONDecoder()
decoder.userInfo[CodingUserInfoKey.context!] = dbContext
coreDataStack.deleteAllRecords("Songs")
_ = try decoder.decode([CategoryManagedObject].self, from: data)