swift - 如何将数据连接到数组以在 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 的输出。
解决方案
这是从领域本地数据库保存和获取数据的代码。将代码正确放置在需要的地方。
// 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
}
}
推荐阅读
- makefile - 了解使用 Make 执行的 shell 命令/配方
- reactjs - 如何连接 Algolia 和 @material-ui
- linux - 如何将 HugePages 与 pmem 分配一起使用?
- python - 为什么,在父类上调用带有self的函数时,子类实际上是在Python中运行的
- c# - 有什么方法可以在 IdentityServer4 中即时更改 client_id 和 client_secret
- ios - Xcode 10 - 以编程方式添加按钮时,滚动视图不允许滚动
- c - 如何在 C 中跟踪特定的函数/文件?
- android - 如何实现对整个RecyclerView的平移和缩放
- angular - Angular cdk-virtual-scroll-viewport 鼠标滚动不能在水平方向上仅使用鼠标滚轮
- java - 是否有将openjdk hs_err_pid 崩溃文件上传给开发人员的流程?