jjzjj

ios - 在获取数据之前加载 TableView

coder 2023-09-13 原文

我使用的应用程序从 HealthKit 检索数据,然后将它们存储在一个数组中。我想要做的是用该数组中的数据加载我的 tableViewController。但不幸的是,当我运行该应用程序时,表格显示为空。

更清楚地说,如果用这些获取的数据填充一个数组(在类的顶部声明),我有一个编码来检索所需数据列表的方法。

我做的是在viewDidLoad函数中调用了这个函数,打印出来的数组是空的,所以我把方法的调用移到了函数viewDidAppear 并打印出数组。该数组已成功填充数据,但我仍然无法使用该数组的数据动态填充行。它仍然显得空白。据我了解,问题是在数组填充数据之前加载了 TableView 。我通过调用方法 self.tableView.reloadData() 尝试了另一种解决方案,但没有成功。

谁能给我解决这个问题的想法?

更新:

这是 viewDidLoad 函数:

override func viewDidLoad() {
    super.viewDidLoad()


    authorizeHealthKit()
    updateLastGlucoRecords()
    println("\(glucoReadings)")
    dispatch_async(dispatch_get_main_queue()) {
        self.tableView.reloadData()
    }

}

这是 viewDidAppear 函数:

override func viewDidAppear(animated: Bool) {
    updateLastGlucoRecords()
    println("Hereeeee2:   \(glucoReadings)")
    dispatch_async(dispatch_get_main_queue()) {
        self.tableView.reloadData()
    }
}

这里是表格应该被数据动态加载的地方:

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

    let df = NSDateFormatter()
    let tf = NSDateFormatter()

    df.dateFormat = "yyyy-MM-dd"
    tf.dateFormat = "hh:mm:ss"

    let readingDateTime = dates[indexPath.row]

    let dateTabel = cell.viewWithTag(100) as! UILabel!
    let timeLabel = cell.viewWithTag(101) as! UILabel!
    let readingLabel = cell.viewWithTag(102) as! UILabel!
    let indicator = cell.viewWithTag(103) as UIView!


    dateTabel.text = df.stringFromDate(readingDateTime)
    timeLabel.text = tf.stringFromDate(readingDateTime)


    let reading = readings[indexPath.row]

    let doubleReading = getRecordDouble(reading)
    readingLabel.text = reading
    let sCase = recordCase(doubleReading!)
    switch (sCase) {
    case "Very low": indicator.backgroundColor = UIColor.redColor()
    case "Too low": indicator.backgroundColor = UIColor.orangeColor()
    case "Normal": indicator.backgroundColor = UIColor.greenColor()
    case "Too high": indicator.backgroundColor = UIColor.yellowColor()
    case "Very High": indicator.backgroundColor = UIColor.orangeColor()
    case "Danger": indicator.backgroundColor = UIColor.redColor()
    default: indicator.backgroundColor = UIColor.grayColor()
    }

    return cell
}

最后是从 HealthKit 中检索数据的方法:

func updateLastGlucoRecords()
{
    // 1. Construct an HKSampleType for weight
    let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodGlucose)
    // 2. Call the method to read the most recent weight sample
    self.healthManager.readRecent10GlucoseReadings(sampleType, completion: {(allReadings, error) -> Void in
        println()
        if (error != nil) {
            println("Error reading glucose readings from HealthKit Store: \(error.localizedDescription)")
            return;
        }

        var glucoseLocalizedString = self.kUnknownString;
        self.glucoses = allReadings as? [HKQuantitySample]
        for reading in self.glucoses! {

            if let record = reading.quantity {
                glucoseLocalizedString = "\(record)"
                let dateTimeRecorded = reading.startDate
                self.glucoReadings.append(glucoseLocalizedString)
                self.glucoDates.append(dateTimeRecorded)
                println("Reading: \(self.glucoReadings), Date: \(self.glucoDates)")
            }
            dispatch_async(dispatch_get_main_queue(), { () -> Void in

            })
        }
    })
}

最佳答案

据推测,您在 HealthKit 中使用的查询包含一个完成处理程序。查询完成时会调用此处理程序,这就是您应该调用 reloadData 的地方。

由于 HealthKit 调用是异步的,您不能依赖于 viewWillAppearviewDidLoad 中填充的数组。

关于ios - 在获取数据之前加载 TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30509963/

有关ios - 在获取数据之前加载 TableView的更多相关文章

  1. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  2. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  3. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  4. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

  5. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  6. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  7. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  8. ruby - 从 Ruby 中的主机名获取 IP 地址 - 2

    我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge

  9. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  10. ruby-on-rails - 获取 inf-ruby 以使用 ruby​​ 版本管理器 (rvm) - 2

    我安装了ruby​​版本管理器,并将RVM安装的ruby​​实现设置为默认值,这样'哪个ruby'显示'~/.rvm/ruby-1.8.6-p383/bin/ruby'但是当我在emacs中打开inf-ruby缓冲区时,它使用安装在/usr/bin中的ruby​​。有没有办法让emacs像shell一样尊重ruby​​的路径?谢谢! 最佳答案 我创建了一个emacs扩展来将rvm集成到emacs中。如果您有兴趣,可以在这里获取:http://github.com/senny/rvm.el

随机推荐