我有一个读取json文件的扩展名,但这不是问题所在。问题是使用集合视图方法更新类中的数组。当我在扩展中打印数组长度时,我得到3,但是当我在集合视图委托方法所在的类中打印时,它会打印0。
extension JSON{
func findmultiple(viewclass: ViewController, @noescape predicate: JSON -> Bool) -> JSON? {
if predicate(self) {
return self
}
else {
if let subJSON = (dictionary?.map { $0.1 } ?? array) {
for json in subJSON {
if let foundJSON = json.findmultiple(viewclass, predicate: predicate) {
let shorten = foundJSON["html"].stringValue
let firstshort = shorten.componentsSeparatedByString(" ")
let secondshort = firstshort[1].componentsSeparatedByString("\r")
let classname = secondshort[0]
if(classname == "STUDY HALL (INSTRUCT)"){
print("skip")
}else{
viewclass.importClass.append(classname)
print("fsgsfg \(viewclass.importgrades.count)") //prints("STUDY HALL", "CHEMISTRY", "PHYSICS")
}
}
}
}
}
return nil
}
}
当我带着方法
去上课时class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource{
var importClass = [String]()
func parseJSON(json: JSON){
let predicate = {
(json: JSON) -> Bool in
if let jsonID = json["class"].string where jsonID == "sg-header-heading"{
return true
}
return false
}
var backclass = ViewController()
let foundJSON = json.findmultiple(backclass, predicate: predicate)
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: colcell = (collection.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as? colcell)!
print(importClass) //prints []
cell.classtitle.text = importClass[indexPath.item] //crashes `index out of range`
}
答案 0 :(得分:1)
在您的ViewController类中,您的变量被定义为 importClasses ,其他地方的 importClass ,这只是如果不是,那么你应该得到一个构建错误。
根据您请求JSON的方式,您可能希望在成功检索到JSON后尝试调用collectionView.reloadData()
。
被修改
findMultiple()
函数正在传递视图控制器的新实例。它应该通过当前的一个。
let foundJSON = json.findmultiple(self, predicate: predicate)
然后您不需要行var backclass = ViewController()