如何确保数据在tableviewcontroller试图加载之前加载

问题描述:

我有一个UITableViewController,并且我得到的问题是nil类的NoMethodError'length' - 因为@data是[],否则在不同的调用时返回行上下文中,我怎样才能确保数据从远程服务加载之前,tableview尝试加载它?如何确保数据在tableviewcontroller试图加载之前加载

def viewDidLoad 
     super 
     loaddata 
    end 

    def loaddata 
     @data =().to_a 
     AFMotion::Client.shared.get("api/v1/user") do |response| 
     if response.success? 
     d = response.object["user"] 
      d.each { 
      |item| 
      aitem = item.new(item) 
      @data << aitem 
      } 
     end 
    end 
    end 

    def tableView(table_view, numberOfRowsInSection: section)           
     @data.length   //error here                    
    end 
+0

是AFMotion ::客户某种支持回调异步方法? – nPn 2014-09-25 12:30:10

这将是(快速解决方案)

def tableView(table_view, numberOfRowsInSection: section)           
    loaddata unless @data 
    @data.length   //error here                    
end 

或者(更红宝石般的解决方案,但需要更多的重构):

更改您的loaddata方法:

def loaddata 
    result = [] 
    AFMotion::client.shared.get("api/v1/user") do |response| 
    if response.success? 
     result = response.object["user"].map { |item| item.new(item) } 
    end 
    end 
    result 
end 

定义新方法:

def data 
    @data ||= loaddata 
end 

现在使用data而不是@data。它会确保每次调用loaddata时首次调用data,并且会缓存该调用的结果。

数点:

  1. 命名约定 - 在Ruby中,我们使用snakecase的方法和变量,如此table_view代替tableView

  2. AFMotion::client - 这是真的很难解析我。是client模块方法(当时应该是相当AFMotion.client),或者是一个模块/类(应该是再AFMotion::Client

+0

谢谢你的建议让我在那里。你是对的,它的AFMotion :: Client,我会更新 – MikeW 2014-09-25 14:15:34