我正在使用一个简单的 UITableViewController
var testdata = [String]()
override func tableView(tableView: UITableView, cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("controlcell",
forIndexPath: indexPath) as! TableViewCell
// Configure the cell...
cell.clabel.text = testdata[indexPath.row]
return cell
}
测试数据在函数外声明。 testdata 也是从另一种方法填充的。
问题是:当我设置断点并检查数据时,self.testdata 显示没有数据。 我是否在 swift 中正确使用了变量?
在这里添加完整的代码:
import UIKit
import Alamofire
class TableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {
struct ListItem {
var Name:String = ""
var Number:String = ""
var Email:String = ""
}
override func viewDidLoad() {
super.viewDidLoad()
getjsonData()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
// return controlstaticdata.count
// return controlListData.controlListItems.count
return testdata.count
}
var testdata = [String]()
func getjsonData(){
var jsondata:NSData!
let url = "http://localhost:3000/controllistapp"
Alamofire.request(.GET, url).responseJSON(){
(_,_,data,_) in
println(data)
// parse the jsondata returned by Alamofire .GET request
let json = JSON(data!)
var i = 0
for(_, subJson): (String, JSON) in json {
if let Name = subJson["Name"].string,
let Number = subJson["Number"].string,
let Email = subJson["Email"].string{
var item = ListItem(Name: Name, Number: Number, Email: Email)
self.testdata += [Name]
}
}
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("controlcell", forIndexPath: indexPath) as! TableViewCell
// Configure the cell...
cell.clabel.text = self.testdata[indexPath.row]
return cell
}
}
getjsonData 中 self.testdata += [Name] 行的断点显示正在填充的数据。 但是,tableView 函数中 cell.clabel.text = self.testdata[indexPath.row] 行的断点显示没有数据并抛出异常。
最佳答案
我认为你的问题是你在将数据填充到数组后忘记包含 self.tableView.reloadData()
关于swift - 无法快速访问在 UITableviewcontroller 函数外声明的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32037980/