将数据从JSON文件加载到表中

时间:2015-07-02 00:43:00

标签: ios json swift

我有一个名为' List'的核心数据模型。具有4个属性,并希望将JSON文件中的数据填充到类型为' List'

的数组中

当我运行应用程序时,它给出了错误'致命错误:数组索引超出范围'

var loadNames = [List]()

var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
var frc: NSFetchedResultsController = NSFetchedResultsController()
func getFetchedResultsController() -> NSFetchedResultsController {
    frc = NSFetchedResultsController(
        fetchRequest: listFetchRequest(),
        managedObjectContext: context,
        sectionNameKeyPath: "done",
        cacheName: nil)
    return frc
}
func listFetchRequest() -> NSFetchRequest {
    let fetchRequest = NSFetchRequest(entityName: "List")
    let doneSortDescriptor = NSSortDescriptor(key: "done", ascending: false)
    let nameSortDescriptor = NSSortDescriptor(key: "firstName", ascending: true)
    fetchRequest.sortDescriptors = [doneSortDescriptor, nameSortDescriptor]
    return fetchRequest
}
func isFrequent(item: List) -> Bool {
    return item.frequent == true
}

override func viewWillAppear(animated: Bool) {
    var readError:NSError?
    let filePath = NSBundle.mainBundle().pathForResource("NameList", ofType:"json")
    let data = NSData(contentsOfFile:filePath!, options: NSDataReadingOptions.DataReadingUncached, error:&readError)
    var jData = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers, error: &readError) as! NSArray

    for i in 0..<jData.count {
        if let jfName = jData[i]["firstName"] as? String {
            if let jlName = jData[i]["lastName"] as? String {
                if let jDone = jData[i]["done"] as? NSNumber {
                    if let jFrequent = jData[i]["frequent"] as? NSNumber {

                        loadNames[i].firstName = jfName //This is where the error is pointing.
                        loadNames[i].lastName = jlName
                        loadNames[i].done = jDone
                        loadNames[i].frequent = jFrequent

                        println(loadNames.count)
                    }
                }
            }
        }
    }
}

变量似乎都是从JSON文件中获取数据以及&#39; i&#39;在&#39; for&#39;发生错误时循环是&#39; 0&#39;。

我不知道为什么会这样。

数组计数返回6,这是JSON文件中的实际对象数量。

1 个答案:

答案 0 :(得分:0)

您应该使用loadNames数组的append方法添加每个List对象。尝试在零长度数组中访问索引i&gt; = 0是导致错误的原因。