如何在Ruby Motion中同步调用HTTP API(How do I synchronously call HTTP api in Ruby Motion)

编程入门 行业动态 更新时间:2024-10-11 17:18:58
如何在Ruby Motion中同步调用HTTP API(How do I synchronously call HTTP api in Ruby Motion)

在我的控制器中,我想等待/阻塞,直到http请求返回数据,然后再尝试加载表。 目前,在设置数据源后获取@data.count时会抛出错误:

def viewDidLoad super self.title = "my categories" @table = UITableView.alloc.initWithFrame(self.view.bounds) @data = nil //how to call this next line synchronously ? create_data @table.dataSource = self self.view.addSubview @table end def create_data BW::HTTP.get("http://website.com/api/v1/category") do |response| if response.ok? p "response was ok" mydata = BW::JSON.parse(response.body.to_str) mydata.each { |item| @data << Item.new(item) p "test" } else warn "problem" end end end

我该怎么做?

In my controller I would like to wait/block until the http request has returned data before attempting to load the table. Currently, it throws error when fetching @data.count after setting datasource:

def viewDidLoad super self.title = "my categories" @table = UITableView.alloc.initWithFrame(self.view.bounds) @data = nil //how to call this next line synchronously ? create_data @table.dataSource = self self.view.addSubview @table end def create_data BW::HTTP.get("http://website.com/api/v1/category") do |response| if response.ok? p "response was ok" mydata = BW::JSON.parse(response.body.to_str) mydata.each { |item| @data << Item.new(item) p "test" } else warn "problem" end end end

How can I do it?

最满意答案

你不应该等待。

您可能只需将@data初始化为空数组即可启动。 这将避免异常并防止需要阻止UI线程,您应该不惜一切代价避免这种情况。

所以更换

@data = nil

@data = []

You shouldn't wait.

You should probably just initialise @data to an empty array to start. This will avoid the exception and prevent the need to block the UI thread, which you should avoid at all costs.

So replace

@data = nil

with

@data = []

更多推荐

本文发布于:2023-08-08 00:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466653.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Motion   Ruby   HTTP   api

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!