我正在使用最新版本的Rubymotion构建iOS应用程序。 我有一个tableview,我想填充来自远程API的数据。
我命名了控制器: ProjectsController
我将模型命名为: Project
在控制器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
这是我在控制器中的viewDidLoad:
def viewDidLoad
super
@projects = Project.load_projects
self.navigationItem.title = "Projekt"
end
我在viewDidLoad中没有像在模型中那样得到相同的响应。在模型方法中,我得到了正确的响应数据,但在viewDidLoad中,我得到了一个返回的“meta”对象。一个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
答案 0 :(得分:3)
我得到的解决方案如下:
BW :: HTTP方法是异步的,因此你的self.load_projects方法将返回一个请求对象,而不是你想要的JSON数据。
基本上BW:HTTP.get立即完成执行,self.load_projects方法返回不正确的数据。
向我建议的解决方案如下:
更改load_projects方法,使其接受视图控制器委托:
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
如果要导入表视图控制器,请不要忘记重新加载数据。
请注意,委托正在调用load_data方法,因此请确保您的视图控制器实现了:
class ProjectsController < UIViewController
#...
Projects.load_projects(self)
#...
def load_data(data)
@projects ||= data
end
#...
end
然后用@projects
做任何你想做的事