【发布时间】:2016-03-31 11:39:05
【问题描述】:
在我的应用程序中使用 Singleton 类,刚刚创建了一个 json 数组。在 UICollectionView 我返回具有共享实例的单例类,如下所示
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("Count: ",InsuranceManager.sharedInstance.InsTypeListArray.count) // Output Count : 0
return InsuranceManager.sharedInstance.InsTypeListArray.count
}
计数始终为“0”。这样集合视图单元格不显示。单例类:
import UIKit
class InsuranceManager {
static let sharedInstance = InsuranceManager()
var InsTypeListArray = [InsuranceType]()
var TypeArray = [InsuranceType]()
var CompListArray = [Companies]()
func getInsuranceDetails() {
if let path = NSBundle.mainBundle().pathForResource("type", ofType: "json") {
do
{
let data = try NSData(contentsOfURL: NSURL(fileURLWithPath: path), options: NSDataReadingOptions.DataReadingMappedIfSafe)
let jsonObj = JSON(data: data)
if jsonObj != JSON.null
{
print("jsonData:\(jsonObj)")
if let items = jsonObj["type"].array
{
// Removing the old data from Insurance type array
self.InsTypeListArray.removeAll()
for item in items
{
var type = InsuranceType()
type.id = item["id"].int
type.name = item["name"].string
type.selectedQuantity = 1
type.imageName = item["imageName"].string
// Adding new data into Insurance type array
self.InsTypeListArray.append(type)
}
print("Insurance List Array Count:\(self.InsTypeListArray.count)")
}
}
else {
print("could not get json from file, make sure that file contains valid json.")
}
}
catch let error as NSError {
print(error.localizedDescription)
}
}
else {
print("Invalid filename/path.")
}
}
}
计数值变为 0,因此集合视图单元格为空。
struct InsuranceType
{
var id: Int?
var name: String?
var selectedQuantity: Int?
var imageName: String?
}
我的json文件是:
{
"type": [
{
"id": 1001,
"name": "Vehicle",
"imageName": "vehicle"
},
{
"id": 1002,
"name": "Health",
"imageName": "health"
},
{
"id": 1003,
"name": "Life",
"imageName": "life"
},
{
"id": 1004,
"name": "House",
"imageName": "home"
},
{
"id": 1005,
"name": "Legal Protection",
"imageName": "legal"
},
{
"id": 1006,
"name": "Travel",
"imageName": "travel"
}
]
}
根据我在 json“类型”文件中的值,希望在 UICollectionView 中显示。任何人都可以帮助我我的代码中的实际问题是什么。提前致谢
【问题讨论】:
标签: ios swift2 uicollectionview