如何从CoreData TableView数组中提取数据数组,将其放入新数组中并将其导出为csv?

时间:2019-06-18 07:50:57

标签: arrays swift csv

我有一个应用程序,它在alertController中接受用户输入,然后将这些值存储在CoreData中,然后将其显示在tableview中。我将所有字符串连接起来,以逗号作为分隔符,以使我更容易导出csv。但是,当我打印出CoreData实体时,会得到一个非常复杂的数组。数组如下所示:

  

[((实体:AlarmItems; id:0xc2bccd37cb753acb;数据:{       alarmAttributes =“示例名称,24/11/2019,1500,True,NIL”;   }),(实体:AlarmItems; id:0xc2bccd37cb653acb;数据:{       alarmAttributes =“示例,12/12/2019,24/11/2019,True,NIL”;   })]

我只想提取alarmAttributes之后的部分,以导出到CSV以便进一步使用。

我看着NSEntityMapping,但是那对我没有帮助。我现在很困。我不知道如何解决这个问题。首先我的方法是否正确?是否有可能使用我创建的数组导出csv?想法是将csv存储在iOS设备中,然后可以通过电子邮件发送到其他地方。

我的ViewController:

class ViewController: UITableViewController {

    var alarmItems: [NSManagedObject] = []
    let cellId = "cellId"


    override func viewDidLoad() {
        super.viewDidLoad()



    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        let managedContext = appDelegate.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "AlarmItems")
        do {
            alarmItems = try managedContext.fetch(fetchRequest)
        } catch let err as NSError {
            print("Failed to fetch items", err)
        }
    }

    @objc func addAlarmItem(_ sender: AnyObject) {
        print("this works")
        let alertController = UIAlertController(title: "Add New Item", message: "Please fill in the blanks", preferredStyle: .alert)
        let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in

            //combined string of attributes
            let myStrings: [String] = alertController.textFields!.compactMap { $0.text }
            let myText = myStrings.joined(separator: ", ")

            self.save(myText)
            self.tableView.reloadData()
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)

        alertController.addTextField { (textField) in
            textField.placeholder = "Enter Name of Engineer"
        }
        alertController.addTextField { (textField) in
            textField.placeholder = "Enter Date of Alarm in DD/MM/YYYY"
        }
        alertController.addTextField { (textField) in
            textField.placeholder = "Enter Time of Alarm in 24h (eg: 2300)"
        }
        alertController.addTextField { (textField) in
            textField.placeholder = "Please indicate True/False (type True or False)"
        }
        alertController.addTextField { (textField) in
            textField.placeholder = "Insert comments (if any), or NIL"
        }


        alertController.addAction(saveAction)
        alertController.addAction(cancelAction)
        present(alertController, animated: true, completion: nil)
    }

    func save(_ itemName: String) {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        let managedContext = appDelegate.persistentContainer.viewContext
        let entity = NSEntityDescription.entity(forEntityName: "AlarmItems", in: managedContext)!
        let item = NSManagedObject(entity: entity, insertInto: managedContext)
        item.setValue(itemName, forKey: "alarmAttributes")

        do {
            try managedContext.save()
            alarmItems.append(item)

        } catch let err as NSError {
            print("Failed to save an item", err)
        }
    }

    @objc func exportCSV(_ sender: AnyObject) {
        //will work on exporting csv in the future
        return
    }

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        let alarmItem = alarmItems[indexPath.row]
    cell.textLabel?.text = alarmItem.value(forKeyPath: "alarmAttributes") as? String
        return cell
    }

}

0 个答案:

没有答案