我正在为一家广播电台创建一个应用程序,我想将“节目”对象存储到数组中。我使用Web服务器提供JSON数据来填充数组,但是我想将这个JSON数据作为字符串存储到CoreData中,以便访问数组不依赖于互联网连接。因此,我希望在应用程序启动时更新CoreData中的字符串,并基于存储在CoreData中的字符串而不是Web服务器上的JSON数据创建数组。
这是我的函数,用于从Web服务器下载JSON数据并将其存储到字符串中:
这是从CoreData获取的JSON创建shows数组的函数:
然而,这样并不能正确地将数据加载到数组中。我在downloadShows()函数中打印了我保存到CoreData中的值(jsonAsString),得到了以下响应:
[{"Name":"Example Show 2","ID":"2","Description":"This ...
但是当我在createShowsArray()函数中从CoreData中获取字符串(arrayAsString)时,它添加了"DOG_Radio.ShowModel"。
[DOG_Radio.ShowModel(Name: "Example Show 2", ID: "2", Description: "This ...
JSON解码器无法将arrayAsString解码为实际数组。它会抛出以下错误:
Error dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 1." UserInfo={NSDebugDescription=Invalid value around character 1.})))
抱歉问题描述有点长,我只是不知道如何使用CoreData将JSON保存为字符串,然后稍后将该字符串转换为数组。
这是我的函数,用于从Web服务器下载JSON数据并将其存储到字符串中:
func downloadShows() {
let urlPath = "http://dogradioappdatabase.com/shows.php"
guard let url = URL(string: urlPath) else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
let jsonAsString = self.jsonToString(json: dataResponse)
DispatchQueue.main.async {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let task2 = WebServer(context: context) // Link Task & Context
task2.showsArray = jsonAsString
print(jsonAsString)
(UIApplication.shared.delegate as! AppDelegate).saveContext()
}
}
task.resume()
}
func jsonToString(json: Data) -> String {
let convertedString: String
convertedString = String(data: json, encoding: String.Encoding.utf8)! // the data will be converted to the string
return convertedString
}
这是从CoreData获取的JSON创建shows数组的函数:
func createShowsArray () -> Array<ShowModel> {
var array: Array<ShowModel> = Array()
var tasks: [WebServer] = []
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do {
tasks = try context.fetch(WebServer.fetchRequest())
}
catch {
print("Fetching Failed")
}
let arrayAsString: String = tasks[0].showsArray!
print(arrayAsString)
do {
let data1 = arrayAsString.data(using: .utf8)!
let decoder = JSONDecoder()
array = try decoder.decode([ShowModel].self, from:
data1)
} catch let parsingError {
print("Error", parsingError)
}
return array
}
然而,这样并不能正确地将数据加载到数组中。我在downloadShows()函数中打印了我保存到CoreData中的值(jsonAsString),得到了以下响应:
[{"Name":"Example Show 2","ID":"2","Description":"This ...
但是当我在createShowsArray()函数中从CoreData中获取字符串(arrayAsString)时,它添加了"DOG_Radio.ShowModel"。
[DOG_Radio.ShowModel(Name: "Example Show 2", ID: "2", Description: "This ...
JSON解码器无法将arrayAsString解码为实际数组。它会抛出以下错误:
Error dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 1." UserInfo={NSDebugDescription=Invalid value around character 1.})))
抱歉问题描述有点长,我只是不知道如何使用CoreData将JSON保存为字符串,然后稍后将该字符串转换为数组。
NSManagedObjects
中的更改,并在下次保存时进行更新。如果您在Core Data中存储了包含数千条记录的JSON blob,并且想要更改一个记录的一个属性,则必须读取整个JSON文件以进行操作,然后将整个JSON blob保存回Core Data。 - RLoniellodeleteAllShows()
类方法。一旦你将NSManagedObjects
添加到数组中,你就可以像普通对象数组一样访问它们并更改它们,例如Shows[index].name = name
,然后通过调用DatabaseController.saveContext()
将更改保存到 CoreData 中。@Purpose,这个问题是关于从 JSON 管理 CoreData 对象,而不是CloudKit
。 - RLoniello