Swift 3中Alamofire的核心数据

问题描述 投票:0回答:1

我正在使用Alamofire解析JSON数据它工作正常。但我的目标是将JSON解析数据存储在CoreData中并在tableView中显示它。我试过很少的代码,但它不适合我

JSON解析数据和OfflineData.xcdatamodeld

enter image description here

enter image description here

这是我的代码:

 var msgdata_store = [Mydata]()
 managedObjextContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

func jsonparsing()
    {

        let Message_dataitems = Mydata(context: managedObjextContext)
        let studentId = "39"
        let params: [String: Any] = ["studentId": studentId]
        let urlString = "http://52.35.124.123/schools/rk/rkapi/api/getmessages"
        guard let url = URL(string: urlString),
            var request = try? URLRequest(url: url, method: .post, headers: nil) else{
                return
        }

        request.httpBody = params.map{ "\($0)=\($1)" }.joined(separator: "&").data(using: .utf8)

        Alamofire.request(request).responseJSON{ response in

            if let result = response.result.value as? [String:Any]
            {

                let arraydata = result["messages"] as? [[String:String]]

                for array_values in arraydata!
                {

                    let content_Vales = array_values["content"]

                    Message_dataitems.content = content_Vales
                }
                do {
                    try self.managedObjextContext.save()

                }catch {
                    print("Could not save data \(error.localizedDescription)")

                }
                self.do_table_refresh()
            }
        }
    }

    func fetchsavedata()
    {
        let presentRequest:NSFetchRequest<Mydata> = Mydata.fetchRequest()

        do {
            msgdata_store = try managedObjextContext.fetch(presentRequest)

            for test in msgdata_store
            {
                let messagecontent = test.content
             print("messagecontent",messagecontent ) as? Any
            }
        }catch {
            print("Could not load data from database \(error.localizedDescription)")
        }
      }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! DetailsTableViewCell

        let row = (indexPath as NSIndexPath).row

        let attendance = msgdata_store[row] as Mydata

        cell.ContentLabel.text = attendance.content

        return cell


    }

    func do_table_refresh(){

        DispatchQueue.main.async(execute: {
            self.Tableview.reloadData()
            return
        })
    }

Mydata+CoreDataProperties,Mydata+CoreDataclass file 

extension Mydata {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Mydata> {
        return NSFetchRequest<Mydata>(entityName: "Mydata")
    }

    @NSManaged public var content: String?

}

@objc(Mydata)
public class Mydata: NSManagedObject {

}

当我运行应用程序时,tableView只显示最后一个值。如何在CoreData中存储数据?请帮我。

json swift core-data swift3 alamofire
1个回答
1
投票

您只创建一个实例,这就是为什么只存在一个实例。

您在此行创建一个实例:

let Message_dataitems = Mydata(context: managedObjextContext)

然后你就有了这个循环:

for array_values in arraydata!
{

    let content_Vales = array_values["content"]

    Message_dataitems.content = content_Vales
}

每次通过此循环都使用相同的Mydata实例。第一遍为content分配一个值,然后每隔一个传递用一个新的覆盖该值。您可能应该在循环中移动创建实例的行,以便您每次都创建一个新实例,而不是反复使用相同的实例。

© www.soinside.com 2019 - 2024. All rights reserved.