2012-11-08 68 views
2

我正在使用最新版本的Rubymotion構建iOS應用程序。 我得到了一個表格,我想填充來自遠程API的數據。無法從模型到控制器獲取Bubblewrap數據

我命名控制器:ProjectsController

我命名型號:項目

在控制器的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中,我得到一個「元」對象返回。 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 

回答

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

+0

謝謝!我正在路上,但不幸的是我無法使用返回的數據。請參閱上面我更新的問題。 –

+0

這已經超出了這個特定問題的範圍,但我建議你調試@person以確保它是你期望的正確對象,因爲錯誤消息說它是一個零對象。 – n00shie

+0

毫米,不確定你的意思?什麼是@person? load_data方法的要點是能夠在控制器的其餘部分使用@projects,對吧? –

相關問題