gpt4 book ai didi

rubymotion - 无法从模型获取 Bubblewrap 数据到 Controller

转载 作者:行者123 更新时间:2023-12-04 05:25:07 24 4
gpt4 key购买 nike

我正在使用最新版本的 Rubymotion 构建一个 iOS 应用程序。
我有一个表格 View ,我想用来自远程 API 的数据填充。

我将 Controller 命名为:ProjectsController

我将模型命名为:项目

在 Controller viewDidLoad 中,我想从 API 获取项目列表。
我在 Project 模型中创建了一个名为 load_projects 的静态方法。

def self.load_projects
BW::HTTP.get("#{URL}projects?id=25&project_id=24&access_token=#{TOKEN}") do |response|
result_data = BW::JSON.parse(response.body)
output = result_data["projects"]
output
end
end

这是我在 Controller 中的 viewDidLoad:
def viewDidLoad
super
@projects = Project.load_projects
self.navigationItem.title = "Projekt"
end

我在 viewDidLoad 中没有得到与在模型中相同的响应。在模型方法中,我得到了正确的响应数据,但在 viewDidLoad 中,我得到了一个返回的“元”对象。一个 BubbleWrap::HTTP::Query 对象。我究竟做错了什么?

更新一

我尝试像这样使用下面的第一个答案,但出现错误:
def tableView(tableView, cellForRowAtIndexPath:indexPath)
cellIdentifier = self.class.name
cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) || begin
cell = UITableViewCell.alloc.initWithStyle(UITableViewCellStyleDefault, reuseIdentifier:cellIdentifier)
cell
end

project = @projects[indexPath.row]['project']['title']
cell.textLabel.text = project
cell
end

错误是:
projects_controller.rb:32:in `tableView:cellForRowAtIndexPath:': undefined method `[]' for nil:NilClass (NoMethodError)
2012-11-09 01:08:16.913 companyapp[44165:f803] *** Terminating app due to uncaught exception 'NoMethodError', reason: 'projects_controller.rb:32:in `tableView:cellForRowAtIndexPath:': undefined method `[]' for nil:NilClass (NoMethodError)

我可以在这里显示返回的数据而不会出错:
def load_data(data)
@projects ||= data
p @projects[0]['project']['title']
end

最佳答案

哈,我刚刚遇到了完全相同的问题。

我得到的解决方案如下:

BW::HTTP 方法是异步的,因此您的 self.load_projects 方法将返回一个请求对象,而不是您想要的 JSON 数据。

本质上 BW:HTTP.get 立即完成执行,而 self.load_projects 方法返回不正确的数据。

向我建议的解决方案如下:

更改您的 load_projects 方法,使其接受 View Controller 委托(delegate):

def self.load_projects(delegate)
BW::HTTP.get("#{URL}projects?id=25&project_id=24&access_token=#{TOKEN}") do |response|
result_data = BW::JSON.parse(response.body)
delegate.load_data(result_data)
delegate.view.reloadData
end
end

如果要导入 TableView Controller ,请不要忘记重新加载数据。

请注意,委托(delegate)正在调用 load_data 方法,因此请确保您的 View Controller 实现:
class ProjectsController < UIViewController

#...

Projects.load_projects(self)

#...

def load_data(data)
@projects ||= data
end
#...
end

然后用@projects 做任何你想做的事

关于rubymotion - 无法从模型获取 Bubblewrap 数据到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13285996/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com