gpt4 book ai didi

ios - 如何将 executeFetchRequest 结果附加到数组结构中

转载 作者:行者123 更新时间:2023-11-28 07:17:46 24 4
gpt4 key购买 nike

我是一名 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
}

最佳答案

您不能使用下标将项目添加到数组中——您需要调用 append() 或使用 += 运算符。试试这个:

self.tasks = task[]()
for element in results {
tasks += task(name: element.name, desc: element.desc)
}

关于ios - 如何将 executeFetchRequest 结果附加到数组结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24716381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com