如何在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 endHow 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 = nilwith
@data = []更多推荐
发布评论