[英]iOS swift tableview cell for parse query data
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
var query = PFQuery(className:"category")
let object = objects[indexPath.row] as String
query.whereKey("type", equalTo:"DRUM")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
for object in objects {
NSLog("%@", object.objectId)
let abc = object["link"]
println("the web is \(abc)")
cell.textLabel!.text = "\(abc)"
}
} else {
NSLog("Error: %@ %@", error, error.userInfo!)
}
}
return cell
}
在將
let object = objects[indexPath.row] as String
無法加載視圖后,刪除僅成功顯示一行的行。
首先,我建議您將單元格數據獲取到cellForRowAtIndexPath之外。 此函數不是從解析接收數據的好地方。 創建另一個函數並創建一個類變量,然后放置從那里獲取數據的句柄。
let object = objects[indexPath.row] as String
for object in objects
盡量不要對不同的東西使用相同的變量名,因為它們會使您感到困惑。
目前看來,這條線沒有任何幫助。 嘗試刪除它:
let object = objects[indexPath.row] as String
首先讓我們牢記原則。 永遠不要從單獨的線程更新UI,因為它的行為是意外的或未定義的。 它工作或工作很奇怪。
其次,您遇到的問題是,當VC加載時,在其中調用tableView的數據源,然后在主線程上調用。 現在,您嘗試通過在單獨的線程中進行異步調用來在單元格上添加一些內容,這將花費一些時間,並且在完成解析調用時主線程不會等待。 如果您在使用Async時遇到困難,請查看文檔,它對於掌握一些術語和原理非常重要。
關鍵是您的主線程從上到下運行,而不必等待每次在單元生成中對異步服務器的調用。 因此,該調用的結果將稍后發布,並且您也不會在主線程上發布。
而且,我建議您不要對大型項目或可管理的代碼庫采用這種方法。 我通常做的是:
我希望我能闡明一些問題。 希望對您有幫助。 干杯!
//a computed var that is initialized to empty array of string or anything you like
//we are observing the value of datas. Observer Pattern.
var datas = [String](){
didSet{
dispatch_async(dispatch_get_main_queue(), {
//we might be called from the parse block which executes in seperate thread
tableView.reloadData()
})
}
}
func viewDidLoad(){
super.viewDidLoad()
//call the parse to fetch the data and store in the above variable
//when this succeeds then the table will be reloaded automatically
getDataFromParse()
}
//get the data: make it specific to your needs
func getDataFromParse(){
var query = PFQuery(className:"category")
//let object = objects[indexPath.row] as String //where do you use this in this block
var tempHolder = [String]()
query.whereKey("type", equalTo:"DRUM")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil && objects != nil {
for object in objects!{
//dont forget to cast it to PFObject
let abc = (object as! PFObject).objectForKey("link") as? String ?? "" //or as! String
println("the web is \(abc)")
tempHolder.append(abc)
}
} else {
print("error") //do some checks here
}
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel!.text = datas[indexPath.row]
return cell
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.