我正在尝试在表视图中显示List实体中的项目。我相信我的问题是一个类型铸造,但经过研究,我一直无法找到解决方案。我的确切错误是“无法指定类型'List'的值来键入'String?'。
以下是代码:
import UIKit
import CoreData
class ToBeastViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var items = [List]()
let matthewsManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let request = NSFetchRequest(entityName: "List")
do {
let response = try matthewsManagedObjectContext.executeFetchRequest(request)
print("Sucess!")
let arrayList = response as! [List]
for item in arrayList {
print(item.item)
}
}
catch {
print("Failed!")
} // numberOfRowsInSection end
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// let cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("MyCell")! as UITableViewCell
let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath)
// var itemString = List as! item
cell.textLabel?.text = items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
}
override func viewDidLoad() {
super.viewDidLoad()
// 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.
}
}
问题在于:
cell.textLabel?.text = items[indexPath.row]
......或者至少这是我的理解。如果格式不佳或者我缺少可能有用的信息,我会道歉。我解决这个问题的一些尝试被注释掉了。谢谢你的帮助!
编辑*
以下是View中的代码,它接受文本输入并将其添加到List:
import UIKit
import CoreData
class JustBeastItViewController: UIViewController {
let matthewsManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
// var items = [List]()
@IBAction func doneButtonPressed(sender: UIBarButtonItem) {
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName("List", inManagedObjectContext: matthewsManagedObjectContext)
let newItem = newManagedObject as! List
newItem.item = justBeastItTextField.text
do {
try matthewsManagedObjectContext.save()
print("It was successful!")
}
catch {
print("There was an error!")
}
let request = NSFetchRequest(entityName: "List")
do {
let response = try matthewsManagedObjectContext.executeFetchRequest(request)
print("Sucess!")
let arrayList = response as! [List]
for item in arrayList {
print(item.item)
}
}
catch {
print("Failed!")
}
}
@IBOutlet weak var justBeastItTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// 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.
}
}