【发布时间】:2016-08-31 16:17:35
【问题描述】:
我对 IOS 编程非常陌生,我刚刚得到以下代码工作正常,但我无法知道 这里的控制流程。
- 怀疑
1)。在 viewDidLoad 方法中,我调用了 getContactListJSON() 方法,在我打印了 tableID 之后,它正在打印空数组,为什么?
2) numberOfSectionsInTableView() 和 tableView(:, cellForRowAtIndexPath indexPath:) 执行的时间和次数?
3)。在 getContactListJSON() 方法中,我正在重新加载 tableView,因为它已经加载了一次,为什么?和
4)。如何在不使用 tableView.reloadData() 的情况下仅在第一次加载时在 tableView 上显示数据?
import UIKit
class TableViewController: UITableViewController {
var tableName = [String]()
var tableID = [String]()
override func viewDidLoad() {
super.viewDidLoad()
getContactListJSON()
print(tableID)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func getContactListJSON(){
let urlString = "http://jsonplaceholder.typicode.com/users"
let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL( string: urlEncodedString!)
var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
let json = JSON(data: data)
let contactsArray = json.arrayValue
dispatch_async(dispatch_get_main_queue(), {
for contacts in contactsArray
{
let id = contacts["id"].stringValue
let name = contacts["name"].stringValue
println( "id: \(id) name: \(name)" )
self.tableName.append(name)
self.tableID.append(id)
}
dispatch_async(dispatch_get_main_queue(),{
self.tableView.reloadData()
})
})
}
task.resume()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableName.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
// Configure the cell...
cell.textLabel?.text = tableID[indexPath.row]
return cell
}
}
【问题讨论】: