很抱歉给您带来不便,我是iOS初学者并遇到问题...
我有一个JSON,CoreData和TableView,JSON从web获取并保存在Documents-Folder中。之后,来自JSON的一些值保存在CoreData中,并且必须使用它填充TableView。 F.E.我们采取event_title ..
我有一个控制器:
import Foundation
import UIKit
import CoreLocation
import CoreData
class QuestListViewController: UIViewController, UITableViewDataSource,UITableViewDelegate {
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let eventscd = [Events]()
@IBOutlet weak var questsTabBarItem: UITabBarItem!
var questCode : String = ""
var numberofcells:Int = 0
@IBOutlet weak var tableView: UITableView!
var numbers:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
let entity = NSEntityDescription.entityForName("Events", inManagedObjectContext: managedObjectContext!)
let events = Events(entity: entity!, insertIntoManagedObjectContext: managedObjectContext)
var error: NSError?
var jsonError:NSError?
let jsonBundle = NSBundle.mainBundle()
let jsonFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]as! String
let jsonPath = jsonFolder.stringByAppendingPathComponent("\(self.questCode).json")
if let data = NSData(contentsOfFile:jsonPath, options:NSDataReadingOptions.DataReadingUncached, error:&jsonError) {
let stringData = NSString(data: data, encoding: NSUTF8StringEncoding)
let jsonDict : NSDictionary? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? NSDictionary
if let err = jsonError {
println("error parsing json")
}
if let jsonDictionary = jsonDict {
println("json parsed successfully")
let json_data = JSON(jsonDictionary).arrayValue
let id = jsonDictionary["id"]!.stringValue
let version: AnyObject = jsonDictionary["version"]!
let title: AnyObject = jsonDictionary["title"]!
let description: AnyObject = jsonDictionary["description"]!
let events_json = jsonDictionary["events"] as! NSArray
let eventNumber: NSNumber = jsonDictionary["events"]!.count as NSNumber
self.numberofcells = events_json.count
}
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
}
// MARK: - Set number of rows
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.numberofcells
}
// MARK: - Create cell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
cell.backgroundColor = UIColor.clearColor()
cell.backgroundView = UIView.new()
cell.selectedBackgroundView = UIView.new()
var imageView = UIImageView(frame: CGRectMake(10, 10, cell.frame.width - 0.3, cell.frame.height - 0.3))
let image = UIImage(named: "event_list_cell.png")
imageView.image = image
cell.backgroundView = UIView()
cell.backgroundView!.addSubview(imageView)
var row = indexPath.row
let eventsc = eventscd[indexPath.row] /////HERE IS FATAL BREAKPOINT
// cell.textLabel?.text = eventTable[row] as? String
cell.textLabel?.text = eventsc.valueForKey("event_title")![row] as? String
return cell
}
}
活动课程: 进口基金会 导入CoreData
@objc(Events) class Events: NSManagedObject {
@NSManaged var title: String
@NSManaged var event_title: String
}
和CoreMap: http://i.imgur.com/5iKwAyn.png
有错误:
On line with "let eventsc = eventscd[indexPath.row]" in Controller
Output: "fatal error: Array index out of range"
我哪里错了?
答案 0 :(得分:0)
这是因为在viewDidLoad
中您将numberOfCells
设置为值>但是eventscd
中没有任何内容。这就是为什么在尝试从eventscd
读取值时,会得到索引超出范围错误。
理想情况下,返回的行数应为eventscd.count
,并且在加载表内容之前应填充eventscd
(或者在获取数据并将值添加到eventscd
后重新加载表)< / p>
答案 1 :(得分:0)
您应该使用NSFetchedResultsController
填充表格视图。查看Xcode模板(New Project - &gt; Master-Detail - &gt; check&#34; Use Core Data&#34;)并检查主控制器。
这比使用数组要好得多(性能,内存,可维护性)。