gpt4 book ai didi

swift - 结构,与核心数据对象类型同名?

转载 作者:搜寻专家 更新时间:2023-10-31 19:32:40 24 4
gpt4 key购买 nike

我可以拥有一个与 Core Data 对象类型同名的结构吗?如果是这样,我如何在代码中区分两者?

编辑:比如我有一个Track核心数据对象,当我从外部读入“track”信息时,它是通过json传入的。由于它是一个托管对象,我没有使用核心数据对象,而是使用了另一种结构。我也计划将此命名为 Track,但是这可能会导致我不确定的冲突,所以目前我将其命名为 TrackStruct。另外,这是正确的方法吗?

谢谢!

最佳答案

好吧,在经历了很多困难之后,我为您制作了一个示例项目。但我在这里发布了主要概念。

You can have the sample project here. Though I've loaded data from a local .plist file. You can check out the loadPersonWithJSON(fromPath:) function's job. Just follow my code commenting.

假设我的 Core-Data 中有一个 Person 实体,它有两个 String 属性 name位置。从 json 中,我得到类型为 [[String:Any]] 的数组。现在我想将我的 json 数据映射到核心数据对象模型。

enum CoreDataError: String, Error {
case NoEntity = "ERROR: No Entity, Check the Entity Name"
}

enum JSONError: String, Error {
case NoData = "ERROR: no data"
case ConversionFailed = "ERROR: conversion from JSON failed"
}

typealias personJSONObjectType = [[String:String]]

class PersonTableViewController: UITableViewController {

var person: [Person] = []

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.loadPersonWithJSON(fromPath: "your json URL in String format")
}

func loadPersonWithJSON(fromPath jsonURLString:String) {
guard let jsonURL = URL(string: jsonURLString) else {
print("Error creating an URL from \(jsonURLString)")
return
}
URLSession.shared.dataTask(with: jsonURL) { (data, response, error) in
do {
guard let data = data else {
throw JSONError.NoData
}
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? personJSONObjectType else {
throw JSONError.ConversionFailed
}

// Here you have your json data. Now map this data to your model object.

// First you need to have your shared App Delegate
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
print("No shared AppDelegate")
return
}

// Use shared App Delegate to have the persistent containers view context as managed object context. This will be used to verify whether your Entity exists or not
let managedObjectContext = appDelegate.persistentContainer.viewContext

// Get the Entity in your core data model
guard let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedObjectContext) else {
throw CoreDataError.NoEntity
}

let persons = json.map({ (personInfo) -> Person in

let personName = personInfo["name"] as? String // use appropriate key for "name"
let personLocation = personInfo["location"] as? String // use appropriate key for "location"

// Get your object as Core data Managed object.
let aPerson = NSManagedObject(entity: entity, insertInto: managedObjectContext) as! Person

// Manipulate core data object with json data
aPerson.name = personName
aPerson.location = personLocation
// Manipulation done

return aPerson
})

self.person = persons
self.tableView.reloadData()

} catch let error as JSONError {
print(error.rawValue)
} catch let error as CoreDataError {
print(error.rawValue)
} catch let error as NSError {
print(error.debugDescription)
}
}.resume()
}
}

附加资源

您可以使用下面的 TableView 数据源方法来检查它是否有效:

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.person.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let aPerson = self.person[indexPath.row]
cell.textLabel?.text = aPerson.name
cell.detailTextLabel?.text = aPerson.location
return cell
}

关于swift - 结构,与核心数据对象类型同名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45093260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com