我是iOS新手开发者。我正在尝试将executeFetchRequest的结果导入到我创建的结构中,以便稍后查看到表中。我在func getTasks()中得到“数组索引超出范围”,我很确定我应该追加它,但不确定如何。
我确信有更好的方法来设置它。现在我只是想让事情发挥作用。但其他建议将不胜感激。
import UIKit
import CoreData
var taskMgr: TaskManager = TaskManager()
struct task {
var name = "Un-Named"
var desc = "Un-Described"
}
class TaskManager: NSObject {
var tasks = task[]()
init() {
super.init()
self.getTasks()
}
func addTask(name: String, desc: String) {
tasks.append(task(name: name, desc: desc))
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
let ent = NSEntityDescription.entityForName("Tasks", inManagedObjectContext: context)
var newTask = Tasks(entity: ent, insertIntoManagedObjectContext: context)
newTask.name = name
newTask.desc = desc
println("Object saved")
context.save(nil)
}
func getTasks() {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
var request = NSFetchRequest(entityName: "Tasks")
request.returnsObjectsAsFaults = false;
var results:NSArray = context.executeFetchRequest(request, error: nil)
if (results.count > 0) {
self.tasks = task[]()
var i = 0
for element in results {
tasks[i].name = element.name // fatal error: Array index out of range
tasks[i].desc = element.desc
i++
}
}
}
}
class Tasks: NSManagedObject {
@NSManaged var name: String
@NSManaged var desc: String
}
答案 0 :(得分:1)
您无法使用下标向数组中添加项目 - 您需要调用append()
或使用+=
运算符。试试这个:
self.tasks = task[]()
for element in results {
tasks += task(name: element.name, desc: element.desc)
}