CoreData实现swift 3

时间:2016-09-21 09:38:10

标签: swift core-data nsfetchrequest

我在项目中实施coredata时遇到问题。它似乎能够保存但不能获取。这是代码

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "Utente", in: context)
    let item = NSManagedObject(entity: entity!, insertInto: context)
    var utente: Profilo? = nil
    let vc = CustomTabBarController() as UIViewController
    let vc1 = LoginController() as UIViewController
    // Configure Fetch Request

    do {
        let request: NSFetchRequest<NSFetchRequestResult> = Profilo.fetchRequest()
        let result = try context.fetch(request) as Profilo
        utente = result as Profilo
        print()
        if utente?.type != nil {
            if utente?.type == "students"{
                print("students")
                    present(vc, animated: true, completion: nil)
            }
            if utente?.type == "parents"{
                print("parents")
                present(vc, animated: true, completion: nil)

            }
            if utente?.type == "teachers"{
                print("teachers")
                present(vc, animated: true, completion: nil)

            }
        } else {
            print("variable type empty")
            present(vc1, animated: true, completion: nil)

        }
    } catch {
        let fetchError = error as NSError
        print(fetchError)
    }

我也在结果行上得到错误: 不能调用&#39;获取&#39;使用类型的参数列表(NSFetchRequest)

2 个答案:

答案 0 :(得分:2)

语法应该是

let request: NSFetchRequest<Profilo> = Profilo.fetchRequest()
let result = try context.fetch(request) as! [Profilo] // returns always an array.

考虑默认的初始值设定项CustomTabBarController()LoginController()无法正常工作。

答案 1 :(得分:1)

我们同意发布我的核心数据功能,但它们可能不是最好的方式,但它们可以在我的项目中工作。我的实体被称为目标。

// MARK: - Core data funcitons

func loadCoreData(){
    goalsArray.removeAll()

    //let request = NSFetchRequest<Goals>(entityName:"Goals")
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

do{
let fetchRequest : NSFetchRequest<Goals> = Goals.fetchRequest() as! NSFetchRequest<Goals>
let sortDescriptor = NSSortDescriptor(key: "id", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]

let result = try context.fetch(fetchRequest)
    for result in result {
        goalsArray.append(result)
        print("Fetched result goaltitle is \(result.goalTitle!)")
    }
    tableView.reloadData()

print("I've fetched the results")
}
catch {
    fatalError("Sthh")
    }
}



func countCoreDataObjects()-> Bool{
           //let request = NSFetchRequest<Goals>(entityName:"Goals")
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    do{
        let fetchRequest : NSFetchRequest<Goals> = Goals.fetchRequest() as! NSFetchRequest<Goals>
        let result = try context.fetch(fetchRequest)
        if result.count == 0 {
            return false
        } else {return true

        }
    }
    catch {
        fatalError("Sthh")
    }

}


func saveToCD(object: goalClassForPassing){

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "Goals", in: context)
    let goal = NSManagedObject(entity: entity!, insertInto: context) as! Goals



    goal.goalTitle = object.goalName
    goal.id = String(describing:Date())
    goal.imagePath = object.imagePath

    do {
        try context.save()}
    catch {
        fatalError("couldn't save to core data")
    }


    goal.id = String(describing: Date())
    goalObjectToSaveToCD?.id = String(describing: NSDate())
    print(goalObjectToSaveToCD?.goalTitle)
    print("Saved \(goal.goalTitle) - \(goal.id) - \(goal.imagePath) to Core Data")
    loadCoreData()
}