草庐IT

ios - 异步查询后 UITableViewController 消失

coder 2024-01-30 原文

希望你能帮我解决问题...我已经尝试解决这个问题好几天了。

我使用 Parse (www.parse.com) 作为我的后端,并将其托管在我自己的 AWS 服务器上。

应用的结构: 在 AppDelegate 中,如果用户已登录,则显示一个 ViewController 来设置我的 SlideMenuControllerSwift ( https://github.com/dekatotoro/SlideMenuControllerSwift ) 和我的 TabBarController。 [ Storyboard][1]

在我的标签栏 Controller 中,我有一个导航 Controller ,它指向一个 UITableViewController,当我单击一行时,它会转到另一个 UITableViewController。

问题: http://imgur.com/izdCBgt

1) 我点击一行,它对我的​​解析数据库执行异步查询

2) 数据填充表然后消失

3) 如果我更改选项卡并返回主选项卡,数据会重新出现

还有

1) 我点击一行,它对我的​​解析数据库执行异步查询

2) 数据填充表然后消失

3) 如果我回到原来的 UITableViewController,它不会正确转换回来,我需要来回切换标签,直到它重新出现

代码:

我使用 storyboard segue 转至文档 TableView Controller 。这是我的 DocumentsTableViewController 中的相关代码:

class DocumentTableViewController: UITableViewController, UIDocumentInteractionControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, MMCropDelegate {

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    print("initDocs")
}

var specificDocs=[Document](){
    didSet{
        dispatch_async(dispatch_get_main_queue(), {
            //we might be called from the parse block which executes in seperate thread
            self.loadView()
        })
    }
}


override func viewDidLoad() {
    tableView.dataSource = self
    tableView.delegate = self

    print("we loadeD")
    super.viewDidLoad()

    navigationItem.title = "Job Documents"

    let cameraButton = UIBarButtonItem(image: UIImage(named: "Camera"), style: .Plain, target: self, action: #selector(self.didPressCamera(_:)))
    navigationItem.rightBarButtonItem = cameraButton

    self.queryForTable()

}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.tableView.reloadData()
}


// Define the query that will provide the data for the table view
func queryForTable() {
    // Run a spinner to show a task in progress
    let progressHUD = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
    progressHUD.label.text = "Loading..."

    //2 using those jobActions to find which documents are mine
    let query = PFQuery(className: Document.parseClassName())
    query.whereKey(Document.jobActionCol(), containedIn: jobActions)
    query.includeKey(Document.documentCategoryCol())
//        do {
//            let test = try query.findObjects()
//            self.specificDocs = test as! [Document]
//            progressHUD.hideAnimated(true)
//        } catch {
//            print("error!")
//        }
// FIND WHY THIS DOESNT WORK....WHAT THE F
        query.findObjectsInBackgroundWithBlock {
            (objects: [PFObject]?, error: NSError?) -> Void in
            if error == nil {
                // The find succeeded.
                self.specificDocs = objects as! [Document]
                print("done")
                progressHUD.hideAnimated(true)

            } else {
               // Log details of the failure
                print("Error: \(error!) \(error!.userInfo)")
            }
        }
    }


    // MARK: - Table view data source

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

    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cellIdentifier")
        if ((cell) == nil){
            cell = UITableViewCell.init(style: .Default, reuseIdentifier: "cellIdentifier")
        }

        cell!.textLabel?.text = specificDocs[indexPath.row].documentCategory!.type!
        print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
//        print(UIApplication.sharedApplication().keyWindow?.performSelector("recursiveDescription"))
        return cell!
    }


    deinit {
        print("docs deinit")
    }
}

最佳答案

哦,现在我明白你代码的意图了。但是,你这样做有什么理由吗?直接调用 loadView() 是不正确的。

tableView.dataSource = self
tableView.delegate = self

移动到 viewWillAppear 中的第一个,除了完成得太快无法从解析中接收外,它将起作用。

Normal way will be like below:

var specificDocs=[Document](){
didSet{
    dispatch_async(dispatch_get_main_queue(), {
        //we might be called from the parse block which executes in seperate thread
        self.loadView()
    })
}

self.loadView() to self.tableView.reloadData().

tableView.dataSource = self
tableView.delegate = self

That doesn't needs.

override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()}

That doesn't needs too.

无论如何,您的代码只需将调用 self.loadView() 修改为 self.tableView.reloadData() 即可

关于ios - 异步查询后 UITableViewController 消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38937581/

有关ios - 异步查询后 UITableViewController 消失的更多相关文章

  1. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  2. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  3. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

  4. 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返回它复制的字节数,但是当我还没有下

  5. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  6. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  7. sql - 查询忽略时间戳日期的时间范围 - 2

    我正在尝试查询我的Rails数据库(Postgres)中的购买表,我想查询时间范围。例如,我想知道在所有日期的下午2点到3点之间进行了多少次购买。此表中有一个created_at列,但我不知道如何在不搜索特定日期的情况下完成此操作。我试过:Purchases.where("created_atBETWEEN?and?",Time.now-1.hour,Time.now)但这最终只会搜索今天与那些时间的日期。 最佳答案 您需要使用PostgreSQL'sdate_part/extractfunction从created_at中提取小时

  8. ruby-on-rails - 在 Ruby on Rails 中发送响应之前如何等待多个异步操作完成? - 2

    在我做的一些网络开发中,我有多个操作开始,比如对外部API的GET请求,我希望它们同时开始,因为一个不依赖另一个的结果。我希望事情能够在后台运行。我找到了concurrent-rubylibrary这似乎运作良好。通过将其混合到您创建的类中,该类的方法具有在后台线程上运行的异步版本。这导致我编写如下代码,其中FirstAsyncWorker和SecondAsyncWorker是我编写的类,我在其中混合了Concurrent::Async模块,并编写了一个名为“work”的方法来发送HTTP请求:defindexop1_result=FirstAsyncWorker.new.async.

  9. ruby-on-rails - environment.rb 中设置的常量在开发模式中消失 - 2

    了解Rails缓存如何工作的人可以真正帮助我。这是嵌套在Rails::Initializer.runblock中的代码:config.after_initializedoSomeClass.const_set'SOME_CONST','SOME_VAL'end现在,如果我运行script/server并发出请求,一切都很好。然而,在我的Rails应用程序的第二个请求中,一切都因单元化常量错误而变得糟糕。在生产模式下,我可以成功发出第二个请求,这意味着常量仍然存在。我已通过将以上内容更改为以下内容来解决问题:config.after_initializedorequire'some_cl

  10. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

随机推荐