首页 > 解决方案 > 如何将数据连接到数组以在 TableView 中使用

问题描述

我正在尝试连接领域过滤器输出的数据。我无法并且在尝试时遇到错误。

我尝试将“营养”输出定义为字符串、整数和浮点数。

这是我的代码:

import UIKit
import RealmSwift

class SecondViewController: UIViewController, UITableViewDataSource {

    var localNumNutrition: Int = 0
    var localNumFoodType: Int = 0
    var localNutrition: String = ""
    var localFoodType: String = ""
    var nutritionRealmData = ["Energ_Kcal", "Protein_g", "Fiber_TD_g", "Sugar_Tot_g", "Calcium_mg", "Iron_mg", "Sodium_mg", "Vit_D_IU", "Cholestrl_mg"]

    func localizeInput() {
        localNumNutrition = numNutrition
        localNumFoodType = numFoodtype
        localNutrition = nutrition
        localFoodType = foodtype
    }

    let testItems = ["Item A: protein", "Item B", "Item C"]
    //var displayItems: [String] = ["No Values: 00.00"]

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "cell")
        cell.textLabel?.text = testItems[indexPath.row]

        return cell

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        localizeInput()

        // Do any additional setup after loading the view, typically from a nib.

        /**Realm
        let realm = try! Realm()
        print(Realm.Configuration.defaultConfiguration.fileURL)
        Bundle.main.path(forResource: _, ofType:)
        */

        func setDefaultRealmForUser(username: String) {
            var config = Realm.Configuration()

            // Use the default directory, but replace the filename with the username
            config.fileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("\(username).realm")

            // Set this as the configuration used for the default Realm
            Realm.Configuration.defaultConfiguration = config
        }

        let config = Realm.Configuration(
            // Get the URL to the bundled file
            fileURL: Bundle.main.url(forResource: "NutritionData", withExtension: "realm"),
            // Open the file in read-only mode as application bundles are not writeable
            readOnly: true)

        //print(config)
        //print(Realm.Configuration.defaultConfiguration.fileURL)

        // Open the Realm with the configuration
        let realm = try! Realm(configuration: config)

        localNutrition = nutritionRealmData[localNumNutrition]

        // Read some data from the bundled Realm
        let results = realm.objects(NutritionData.self).filter("App_Food_Pyramid_Category =" + String(localNumFoodType)).sorted(byKeyPath: localNutrition, ascending: false)
        let nutritionValuesResults = results.value(forKeyPath: localNutrition)
        let shortDesc = results.value(forKeyPath: String("Shrt_Desc"))
        //print(results)
       // print(shortDesc)
       // print(nutritionValuesResults)

        /*
        for (let i = 0; results.length - 1; i++) {
            let item = results[i];
        }
        */
        var itemCount: Int = 0
        for item in results {
            itemCount = itemCount + 1
            if itemCount < 10 {
                let desc = String(item.Shrt_Desc!)
                let nutritionValue = item.value(forKeyPath: localNutrition) **These are the 2 outputs**

                //let stringNutritionValue = NSNumber(nutritionValue)
                let displayItems = [(String(desc) + String(nutritionValue)] **Trying to join them to get a single output.**

                //print(displayItems)

                print(desc)
                print(nutritionValue)
            }
        }

        //print(item)

        /*
        var iterator = results.makeIterator()
        let NutritionDataNext = iterator.next()
        print(next)
        */

        navigationController?.navigationBar.prefersLargeTitles = true

    }


}

我正在尝试将 desc (描述)和 NutritionValue (十进制)加入一个数组以用作表格视图的数据。我试图让数据显示为 desc: NutritionValue 的输出。

标签: swift

解决方案


这是从领域本地数据库保存和获取数据的代码。将代码正确放置在需要的地方。

// Realm Object
class NutritionData: Object {
    @objc dynamic var desc = ""
    @objc dynamic var nutritionValue = 0.0

    // Setting data to realm object
    func setAllProperties(_ desc: String, value: Double) {
        self.desc = desc
        self.nutritionValue = value
    }
}


class SecondViewController: UIViewController, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    var testItems = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        testItems = getData()
        tableView.reloadData()
    }

    func saveData() {
        let realm = try! Realm()
        try! realm.write {
            let object = NutritionData()
            object.setAllProperties("Some description", value: 10.5)

            // Saving the realm object to local database.
            realm.add(object)
        }
    }

    func getData() -> [String] {
        // retrieving the saved data with filter.
        let data = Realm().objects(NutritionData.self).filter("nutritionValue == 10.5")

        // mapping the realm's result to desired object.
        let strings = data.map { item: NutritionData -> String
            return "\(item.desc): \(item.nutritionValue)"
        }

        // Returning the data to populate in the tableView.
        return strings
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "cell")
        cell.textLabel?.text = testItems[indexPath.row]
        return cell
    }
}

推荐阅读